I am getting the following error::
Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'es2022', 'esnext', 'commonjs', 'amd', 'system', 'umd', 'node16', or 'nodenext'.
14 { path: "auth", loadChildren: ()=> import("./auth/auth.module").then(m=>m.AuthModule)},
this is the file that is giving me the issue:
const routes: Routes = [
{ path: "", component: PostListComponent },
{ path: "create", component: PostCreateComponent, canActivate: [AuthGuard] },
{ path: "edit/:postId", component: PostCreateComponent, canActivate: [AuthGuard] },
// { path: "auth", loadChildren: "./auth/auth.module#AuthModule"}, // old line being replaced
{ path: "auth", loadChildren: ()=> import("./auth/auth.module").then(m=>m.AuthModule)}, // new line that replaced old line
{ path: "jobCreate", component: JobCreateComponent, canActivate: [AuthGuard]},
];
I found this article online that had the same issue I had:: https://bobbyhadz.com/blog/typescript-dynamic-imports-only-supported-when-module
Angular 8 - Lazy loading modules : Error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'
I tried to modify the tsconfig.json file to the following::
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "commonjs", // 👈️ set to esnext
// "module": "esnext", // I tried this and it didnt work either
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
"node_modules/#types"
],
"lib": [
"es2017",
"dom"
]
}
}
question:
how do i fix this?
I am not sure which node_module this is dependent on, but could I possible reverse to a earlier version to avoid this issue?
Related
The AWS compilation errors from within node_modules are occurring the build
ERROR in ../../../node_modules/#aws-sdk/client-dynamodb/models/models_0.ts 6321:51-59
TS2339: Property '$unknown' does not exist on type 'never'.
6319 | if (obj.NULL !== undefined) return { NULL: obj.NULL };
6320 | if (obj.BOOL !== undefined) return { BOOL: obj.BOOL };
> 6321 | if (obj.$unknown !== undefined) return { [obj.$unknown[0]]: "UNKNOWN" };
| ^^^^^^^^
6322 | };
6323 | }
6324 |
webpack compiled with 9 errors in 6844 ms
I have just updated AWS
"#aws-sdk/client-dynamodb": "^3.51.0",
"#aws-sdk/lib-dynamodb": "^3.51.0",
"#aws-sdk/util-dynamodb": "^3.51.0",
With webpack
const path = require('path');
const slsw = require('serverless-webpack');
const nodeExternals = require('webpack-node-externals');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
/*
This line is only required if you are specifying `TS_NODE_PROJECT` for whatever
reason.
*/
// delete process.env.TS_NODE_PROJECT;
module.exports = {
context: __dirname,
mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
entry: slsw.lib.entries,
devtool: slsw.lib.webpack.isLocal ? 'eval-cheap-module-source-map' : 'source-map',
resolve: {
extensions: ['.mjs', '.json', '.ts'],
symlinks: false,
cacheWithContext: false,
plugins: [
new TsconfigPathsPlugin({
configFile: './tsconfig.paths.json',
}),
],
},
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, '.webpack'),
filename: '[name].js',
},
target: 'node',
externals: [nodeExternals()],
module: {
rules: [
{
// Include ts, tsx, js, and jsx files.
test: /\.(ts|js)x?$/,
exclude: [
path.resolve(__dirname, 'node_modules'),
path.resolve(__dirname, '.serverless'),
path.resolve(__dirname, '.webpack'),
],
use: [
{
loader: 'ts-loader',
options: {
transpileOnly: true,
}
},
'babel-loader'
]
}
]
},
plugins: [new ForkTsCheckerWebpackPlugin()],
};
And ts-config
{
"extends": "./tsconfig.paths.json",
"compilerOptions": {
"lib": ["ESNext"],
"moduleResolution": "node",
"esModuleInterop": true,
"noUnusedParameters": false,
"noUnusedLocals": false,
"resolveJsonModule": true,
"removeComments": true,
"sourceMap": true,
"target": "ES2020",
"outDir": "lib",
"paths": {
"#functions/*": ["src/functions/*"],
"#libs/*": ["src/libs/*"],
"#api/*": ["src/api/*"],
"~/*": [
"./*"
]
},
"types": [
"#types/node",
"#types/jest"
]
},
"include": ["src/**/*.ts", "serverless.ts"],
"exclude": [
"util/**/*",
"node_modules/**/*",
".serverless/**/*",
".webpack/**/*",
"_warmup/**/*",
".vscode/**/*" ],
"ts-node": {
"require": ["tsconfig-paths/register"]
}
}
Webpack looks to be still compiling node_modules regardless of it being in the excluded list.
Stop typescript type lookup traversing parent nodes
Incompatible types found by going up directories
Alter tsconfig.json to include typeRoots as a parameter as per Prevent require(...) from looking up modules in the parent directory
{
"extends": "./tsconfig.paths.json",
"compilerOptions": {
"lib": ["ESNext"],
"allowSyntheticDefaultImports": true,
"moduleResolution": "node",
"module": "commonjs",
"esModuleInterop": true,
"noUnusedParameters": false,
"noUnusedLocals": false,
"resolveJsonModule": true,
"removeComments": true,
"sourceMap": true,
"target": "ES2020",
"outDir": "lib",
"paths": {
"#functions/*": ["src/functions/*"],
"#libs/*": ["src/libs/*"],
"#api/*": ["src/api/*"],
"~/*": [
"./*"
]
},
"typeRoots": [
"./"
],
"types": [
"#types/node",
"#types/jest"
]
},
"include": ["src/**/*.ts", "serverless.ts"],
"exclude": [
"util/**/*",
"node_modules",
"node_modules/**/*",
".serverless/**/*",
".webpack/**/*",
"_warmup/**/*",
".vscode/**/*"
],
"ts-node": {
"require": ["tsconfig-paths/register"]
}
}
I am working on creating a webpack plugin. I have used typescript to code the plugin. I am trying to bundle the plugin code before I publish it on NPM. I am getting exception that my plugin class is not a constructor.
Please find below the directory structure:-
tsconfig.json:-
{
"compilerOptions": {
// Target latest version of ECMAScript.
"target": "es5",
// Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'.
"module": "commonjs",
// Search under node_modules for non-relative imports.
"moduleResolution": "node",
// Process & infer types from .js files.
"allowJs": true,
// Don't emit; allow Babel to transform files.
"noEmit": false,
"pretty": true,
// Enable strictest settings like strictNullChecks & noImplicitAny.
"strict": true,
// Disallow features that require cross-file information for emit.
"isolatedModules": true,
// Import non-ES modules as default imports.
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"outDir": "dist/"
},
"include": [
"src"
],
"exclude": [
"dist",
"node_modules"
]
}
Webpack config:-
const path = require('path');
module.exports = {
name: 'log-stylizer-webpack-plugin',
entry: './src/index.ts',
output: {
filename: 'index.bundle.js',
path: path.resolve(__dirname, 'dist'),
},
mode: 'development',
target: 'node',
module: {
rules: [
{
test: /\.ts?$/,
use: 'ts-loader',
exclude: /node_modules/,
}
]
},
resolve: {
extensions: ['.ts']
}
};
In order to build a thing as a library with webpack, you have to specify the option output.libraryTarget to export things.
{
output: {
// ...
// `umd` is always a best choice in most cases
// since it would work for all kind of module styles
libraryTarget: 'umd',
}
}
I'm trying to run jest with typescript, but I'm getting following error. The project runs fine in webpack and with ts-node. For some reason I can't get it to work with jest.
FAIL src/__tests__/classes/Utils.spec.ts
● Test suite failed to run
Cannot find module 'typescript'
Require stack:
- /Users/myuser/repos/project/node_modules/ts-jest/dist/config/config-set.js
- /Users/myuser/repos/project/node_modules/ts-jest/dist/ts-jest-transformer.js
- /Users/myuser/repos/project/node_modules/ts-jest/dist/index.js
- /Users/myuser/repos/project/node_modules/#jest/transform/build/ScriptTransformer.js
- /Users/myuser/repos/project/node_modules/#jest/transform/build/index.js
- /Users/myuser/repos/project/node_modules/jest-runtime/build/index.js
- /Users/myuser/repos/project/node_modules/#jest/core/build/cli/index.js
- /Users/myuser/repos/project/node_modules/#jest/core/build/jest.js
- /Users/myuser/repos/project/node_modules/jest/node_modules/jest-cli/build/cli/index.js
- /Users/myuser/repos/project/node_modules/jest/node_modules/jest-cli/bin/jest.js
- /Users/myuser/repos/project/node_modules/jest/bin/jest.js
- /usr/local/lib/node_modules/jest/node_modules/import-local/index.js
- /usr/local/lib/node_modules/jest/bin/jest.js
jest.config.js
This is the configuration. I've tried many variations on the roots property and moduleNameMapper, but the error message is exactly the same no matter what I change in the config.
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
moduleDirectories: ['node_modules', 'src'],
moduleNameMapper: {
'^src/(.*)$': '<rootDir>/src/$1',
}
};
tsconfig.json
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"src/*": ["src/*"],
"tests/*": ["__tests__/*"]
},
"target": "es6",
"module": "commonjs",
"esModuleInterop": true,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true,
"inlineSourceMap": false,
"outDir": "dist",
"lib": ["es6", "dom", "esnext", "esnext.asynciterable"],
"typeRoots": ["node_modules/#types", "src/typings"]
},
"awesomeTypescriptLoaderOptions": {
"useBabel": true,
"useCache": true,
"useTranspileModule": true
},
"include": ["src/**/*.ts"],
"exclude": ["./node_modules/*"]
}
Utils.spec.js
import { Utils } from 'src/utils/classes/Utils';
test('Generates a 6 digit number'), () => {
expect(Utils.randomNumberGenerator(6).toHaveLength(6))
});
Utils.ts
export class Utils {
public static randomNumberGenerator(length: number): number {
const baseNumber: number = Number(1 + '0'.repeat(length - 1));
const randomMultiplier: number = Math.floor(Math.random() * Number('9' + '0'.repeat(length - 1)));
const randomToken: number = baseNumber + randomMultiplier;
return randomToken;
}
}
#tmhao kindly helped me with this issue.
Problem was that ts-jest was not installed. A bit unclear error message.
I am trying to implement encryption into my project using vuejs and typescript. I successfully implemented it in the .vue file, but when I try to write the encryption into a typescript class, the mocha test runs it, but when I try to compile and open it in the browser i get a javascript error in the console:
app.js:128620 Uncaught ReferenceError: require is not defined
at Object.crypto (app.js:128620)
at __webpack_require__ (app.js:20)
at Object../resources/ts/Classes/Model/Crypter.ts (app.js:125233)
at __webpack_require__ (app.js:20)
at Object../resources/ts/Controller/AuthController.ts (app.js:125924)
at __webpack_require__ (app.js:20)
at Object../node_modules/babel-loader/lib/index.js?!./node_modules/babel-
loader/lib/index.js!./node_modules/vue-
loader/lib/index.js?!./resources/js/Components/Includes/Login.vue?
vue&type=script&lang=js& (app.js:3308)
at __webpack_require__ (app.js:20)
at Module../resources/js/Components/Includes/Login.vue?
vue&type=script&lang=js& (app.js:124322)
at __webpack_require__ (app.js:20)
The marked line in the app.js is:
module.exports = require("crypto");
I already tried different importing 'strategies' in the typescript file like:
import * as crypto from "crypto";
import crypto from "crypto";
var crypto = require("crypto");
And also adding this in the webpack.mix.js
"node": {
fs: "empty",
crypto: true,
http: true,
https: true,
os: true,
vm: true,
stream: true,
path: true
},
but it didn't work.
The Crypter.ts
import crypto from "crypto";
export default class Crypter {
public constructor() {
}
public static publicEncrypt(data: JSON, publicKey: string): string{
let dataStr = JSON.stringify(data);
let dataB64 = Buffer.from(dataStr).toString("base64");
var buffer = Buffer.from(dataB64);
return crypto.publicEncrypt(publicKey, buffer).toString("base64");
}
}
The tsconfig.json
"compilerOptions": {
"allowUnreachableCode": false,
"allowUnusedLabels": true,
"alwaysStrict": true,
"charset": "utf8",
"declaration": true,
"declarationDir": "resources/ts/lib/types",
"declarationMap": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"importHelpers": true,
"lib": ["ES5", "ES6", "DOM", "DOM.Iterable", "ScriptHost"],
"locale": "en",
"module": "commonjs",
"moduleResolution": "node",
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitUseStrict": false,
"noUnusedParameters": true,
"outDir": "public/js",
"baseUrl": "resources/",
"paths": {
"Base/*": [ "ts/*" ],
"#js/*": [ "js/*" ],
"#ts/*": [ "ts/*" ],
"Component/*": [ "ts/Components/*" ],
"Interface/*": [ "ts/Interfaces/*" ],
"Model/*": [ "ts/Model/*" ],
"Controller/*": [ "ts/Controller/*" ],
"Helper/*": [ "ts/Helper/*" ]
},
"pretty": true,
"sourceMap": true,
"target": "ES5",
"typeRoots": [
"node_modules/#types"
],
"downlevelIteration": true
},
"include": [
"resources/ts/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
],
"files": [
"./node_modules/#types/node/index.d.ts"
]
}
I expect the error to be resulting from wrong compiling or other misconfigurations.
You can't access nodejs crypto module in a web application. Node.js uses the same javascript syntax, but is not running in the browser.
You may need to install another crypto library such as crypto-js, that you can install using npm install crypto-js. There are probably plenty of other libraries that you can choose from (some ideas)
Regarding to the webpack docs for external libraries and nodejs, there is the information that one should be able to import node modules. This works perfectly unless I want to import http2. It prints the following error:
ERROR in ./src/index.ts
Module not found: Error: Can't resolve 'http2' in 'absolutepath/to/src'
The entry typescript file simplified looks like this:
import { readFileSync } from 'fs';
import { createSecureServer } from 'http2';
const server = createSecureServer({...});
And the webpack configuration file looks like follows:
const path = require('path');
module.exports = {
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js'
},
node: {
global: true,
process: true,
fs: 'empty',
http2: 'empty'
},
module: {
rules: [
{ test: /\.ts$/, use: 'ts-loader' }
]
},
resolve: {
extensions: [".ts", ".tsx", ".js"],
modules: [path.resolve(__dirname, '/src'), 'node_modules/'],
descriptionFiles: ['package.json']
},
mode: 'production'
}
And the tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"experimentalDecorators": true,
"target": "es5",
"module": "commonjs",
"emitDecoratorMetadata": true,
"outDir": "dist",
"declaration": false,
"sourceMap": true,
"removeComments": true,
"moduleResolution": "node",
"strict": true,
"noImplicitAny": false,
"typeRoots": [
"node_modules/#types"
],
"lib": [
"es2017"
]
}
}
E.g. importing fs works without errors. I also have seen the node-libs-browser plugin where the http2 module is not listed. But I don't want to use http2 within the browser but just for bundling my backend application. Any suggestions or ideas?
Thanks and cheers!