I'm studying the jsconfig.json file, the documentation doesn't mention explicitly whether it works with "import" and "require", or just "import".
This is the jsconfig.json I created (for Express project):
{
"compilerOptions": {
"baseUrl": "./",
"module": "CommonJS",
"target": "es2020",
"paths": {
"#/controllers/*": ["controllers/*"],
}
},
"exclude": ["node_modules", "**/node_modules/*"]
}
I can't do like this:
const userController = require('#/controllers/user-controller');
// Error: Cannot find module '#/controllers/user-controller'
Why can't I use "require"? I Tried it in React and it worked with "import".
Related
In my project I have to store app and backend inside single repository. And now I have a problem because i need to create shared folder where i have to place every types needed in app and also in backend folder.
So I create shared folder and this is my project structure:
- project
-- app
--- tsconfig.json
--- package.json
-- shared
--- enums
--- interfaces
--- index.ts //exported enums and interfaces
-- backend
--- tsconfig.json
and this is my tsconfig.json inside app
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"declaration": true,
"jsx": "react-jsx",
"moduleResolution": "node",
"baseUrl": ".",
"outDir": "./dist",
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["dom", "dom.iterable"],
"incremental": true,
"allowSyntheticDefaultImports": true,
"rootDirs": ["./src", "../shared"],
"paths": {
"#shared/*": ["../shared/*"]
}
}
// "exclude": ["node_modules"],
// "include": ["src/**/*", "../shared/*"]
}
can someone tell me why when I import something from shared like here:
import { AccountRole } from "#shared/index";
then tsc compiler throw me in console this:
ERROR in ./src/App.tsx 20:0-44
Module not found: Error: Can't resolve '#shared/index' in 'C:\Users\...\Desktop\...\...\app\src'resolve '#shared/index' in 'C:\Users\...\Desktop\...\...\app\src
Thanks for any help!
As I understand it, interfaces are only relevant in Typescript and the tsc compiler should be smart enough not to convert them to JS files in the final output. When I compile my code the interfaces are being compiled with it. Why is this?
My simplified project structure
src/
index.ts
lib/
EventClient.ts
interfaces/
EventClientConfig.ts
What it compiles to
dist/
index.js
lib/
EventClient.js
interfaces/
EventClientConfig.js
My tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"outDir": "./dist",
"lib": ["ES6", "DOM"],
"target": "ES2018",
"module": "CommonJS",
"moduleResolution": "node",
"esModuleInterop": true,
"resolveJsonModule": true,
"baseUrl": ".",
"removeComments": true,
"strict": true,
"typeRoots": ["./node_modules/#types"],
"rootDir": "./src",
"types": [
"node",
"jest-fetch-mock",
"express",
"reflect-metadata"
]
},
"include": ["src"],
"exclude": ["dist", "node_modules", "**/*spec.ts"]
}
An interface
export interface EventClientConfig {
endpoint: string;
authToken: string;
}
How I'm using the interface
import { EventClientConfig } from '../interfaces/EventClientConfig';
const config: EventClientConfig = {
endpoint: '/api',
authToken: '123456'
}
What the interface is compiled to
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
In the compiled code EventClient.js makes no actual reference to the EventClientConfig.js so it's definitely not required. Why is Typescript compiling the interface files to JS?
This was solved thanks to #AluanHaddad who suggested using .d.ts declaration files. I have changed all my interface filenames so that they end with .d.ts and they are no longer included in the output.
The answer to your questions is here modules
In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).
I'm creating an Angular library and within tsconfig.lib.json I've added the following paths configuration:
"compilerOptions": {
"outDir": "../../out-tsc/lib",
"target": "es2015",
"declaration": true,
"inlineSources": true,
"types": [],
"lib": [
"dom",
"es2018"
],
"paths": {
"#fs/*": ["src/lib/*"]
}
}
However attempting to import things like:
import { Test } from '#fs/Test'
Does not work. Anyone know if Angular libraries support hte paths configuration option within tsconfig.lib.json?
Generally I use typescript-transform-paths to perform path transformation on the compiled result, and I was hoping Angular had baked something like this in for libraries?
Try using the following pattern in your tsconfig.json file :
"paths": {
"#services/*": ["app/path/to/services/*"],
"#components/*": ["app/path/to/some/deeply/nested/component/*"],
"#environments/*": ["environments/*"]
},
Then when importing:
import { yourServiceClass } from "#services/yourServiceClass";
I have written a project on Typescript and setup to bundle it with webpack.
Main functionality is wrapped in one Main class, but it imports also other classes.
Need to export Main class and all dependent in to one bundle.js library to use in in other sites.
I've tried to bundle classes in separate project (without webpack just tsc).
this is tsconfig.json:
{
"compilerOptions": {
"module": "amd",
"target": "ES2015",
"declaration": true,
"outDir": "./dist",
"outFile": "./dist/index.js",
},
"include": [
"src/**/*"
]
}
but it is not usable since the error:
ReferenceError: define is not defined
compilled code contains edfine
define("Globals", ["require", "exports"], function (require, exports) {
and also with webpack but not sure have correct setup
the bundle file start with
(function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
in other words I have some classes:
Main.ts
A.ts
B.ts
C.ts
and I expected to get bundle.js file and use like this:
<script type="text/javascript" src="mylib/dist/index.js"></script>
//...
var a = new Main();
but stuck with understanding how it should Typescript and Jsvascript work together.
Will appreciate any help
Update:
Managed to solve with webpack. Main is asccessible from entry app.ts when compiled. So inside app.ts added window.onload handler and assigned class to window scope.
window.onload = function () {
window['MyClass'] = Main;
May be missing something but couldn't find good documentation about writing library on TypeScript for browsers.
Update2:
Ok. found answer. webpack option library works fine.
output: {
filename: "bundle.js",
path: __dirname + "/dist",
library: "MyMainClass"
},
also had to change tsconfig.json target option from es6 to es5
{
"compilerOptions": {
"baseUrl": ".",
"paths": { "*": ["types/*"] },
"lib": [
"dom",
"es6",
"dom.iterable",
"scripthost"
],
"module": "commonjs",
"target": "es5"
},
"exclude": [
"node_modules"
]
}
When I updated Angular from 7 to Angular 8, getting error for lazy loading modules
I have tried the options, which are there in the angular upgradation guide
Made the below changes:
Before
loadChildren: '../feature/path/sample-
tage.module#SameTagModule'
After
loadChildren: () => import('../feature/path/sample-
tags.module').then(m => m.CreateLinksModule)
error TS1323: Dynamic import is only supported when '--module' flag is
'commonjs' or 'esNext'.
You are using dynamic import so you have to change your tsconfig.json like this to target your code to esnext module
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "esnext", // add this line
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "es2015",
"typeRoots": [
"node_modules/#types"
],
"lib": [
"es2018",
"dom"
]
}
}
Also make sure to check tsconfig.app.json dont have module and target config something like this
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"include": [
"src/**/*.ts"
],
"exclude": [
"src/test.ts",
"src/**/*.spec.ts"
]
}
Just want to add my experience to #Tony's answer.
After changing tsconfig.json it still showed an error (red underline). Only after reopening the editor (I used VSCode) did I see the red underline disappear.
Just adding to #Tony's anwser, you might also need to do the same (change to "module": "esnext" ) in the tsconfig.app.json. In my case the tsconfig.json was already using esnext as the module but the tsconfig.app.json was still using es2015 and that caused this error.
I think the proper way to do this is to adjust tsconfig.app.json rather than tsconfig.json.
tsconfig.app.json
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"baseUrl": "./",
"module": "esnext",
"types": []
},
"exclude": [
"test.ts",
"**/*.spec.ts"
]
}
tsconfig.app.json is the Typescript configuration file specific to the app that sits beneath the root of the Angular workspace. The tsconfig.app.json exists so that if you are building an Angular workspace that has multiple apps in it, you can adjust the Typescript configuration separately for each app without having to write redundant configuration properties that overlap between the apps (hence the extends property).
Technically, you don't need tsconfig.app.json at all. If you delete it, you will have to place the "module": "esnext" in tsconfig.json. If you keep it there, it will take precedence over tsconfig.json, so you only need to add the "module":"esnext" line in tsconfig.app.json.
I resolved this issue only by adding
"include": ["src/**/*.ts"]
in my tsconfig.app.json file.
Just update the angular version by giving below command. The errors will disappear.
ng update #angular/core #angular/cli --next
After that, change the target and module in tsconfig.json file
"target": "esnext",
"module": "esnext",
i resolve this error by by doing following steps
step 1:
"module": "es2015" to
"module": "AMD" in tsconfig.json
step 2:
create a new file tsconfig.app.json in app root directory, copy code of Tony Ngo and paste into, then this problem will be resolved.
My angular version is 8.2 and I fixed it by just changing "module": "es2015" to "module": "es2020"
If you are using Ionic framework and VSCode you need to update your Typescript IDE version (> 4)!
I had this issue with angular 13, I noticed that some services had this issue while others didn't, the difference was
#import { Injectable } from '#angular/core/';
while this perfectly compiled without no issues on angular 9 but the fix was to remove the / at the end to become'
#import { Injectable } from '#angular/core';