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!
Related
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?
I'm setting app a new TypeScript/React Project using the following module https://www.npmjs.com/package/#adobe/leonardo-contrast-colors
Using node v16.17.0.
To start with I replicate the example in the README.md but the import doesn't work. Doing the following:
import { Theme, Color, BackgroundColor } from '#adobe/leonardo-contrast-colors';
returns:
Module '"#adobe/leonardo-contrast-colors"' has no exported member 'Theme'.
Module '"#adobe/leonardo-contrast-colors"' has no exported member 'Color'.
Module '"#adobe/leonardo-contrast-colors"' has no exported member 'BackgroundColor'.
Apparently '#adobe/leonardo-contrast-colors' leads to index.d.ts
and if I try to import the members like this:
import { Color } from "#adobe/leonardo-contrast-colors/color.mjs";
neither it works as I get:
Package path ./color.mjs is not exported from package /Users/.../package.json)
I see this open issue in the package repo: https://github.com/adobe/leonardo/issues/173
but backing to 1.0.0-alpha.13 turns out the same for me.
This is my tsconfig
{
"compilerOptions": {
"allowJs": true,
"esModuleInterop": true,
"target": "ES2015",
"jsx": "react",
"typeRoots": ["./node_modules/#types"],
"module": "ESNext",
"moduleResolution": "Node",
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true
},
"include": ["src/**/*.ts", "src/**/*.tsx"]
}
And webpack.config.js:
module.exports = (env, argv) => ({
...
module: {
rules: [
// Converts TypeScript code to JavaScript
{
test: /\.tsx?$/,
use: "ts-loader",
exclude: /node_modules/,
},
...
],
},
resolve: { extensions: [".tsx", ".ts", ".jsx", ".js"] },
...
});
Is this a problem with the package or my project cofiguration?
Thanks in advance
Here is webpack.config.ts
// const path = require("path");
import path from "path";
import HtmlWebpackPlugin from "html-webpack-plugin";
import CopyWebpackPlugin from "copy-webpack-plugin";
import webpack from "webpack";
import WebpackDevServer from "webpack-dev-server";
declare module "webpack" {
interface Configuration {
devServer?: WebpackDevServer.Configuration;
}
}
const config: webpack.Configuration = {
mode: "development",
target: "web",
entry: ["regenerator-runtime/runtime", "./src/index.tsx"],
output: {
filename: "bundle.js",
path: path.join(__dirname, "build"),
publicPath: "/",
},
resolve: {
extensions: [".ts", ".tsx", ".js", ".css"],
alias: {
// add as many aliases as you like!
components: path.resolve(__dirname, "src/components"),
},
fallback: {
// path: require.resolve("path-browserify"),
fs: false,
assert: require.resolve("assert/"),
os: require.resolve("os-browserify/browser"),
constants: require.resolve("constants-browserify"),
},
},
devtool: "eval-cheap-source-map",
module: {
rules: [
{ test: /\.(ts|tsx)/, loader: "babel-loader", exclude: /node_modules/ },
{ test: /\.css$/, use: ["style-loader", "css-loader"] },
{
test: /\.(woff(2)?|ttf|eot)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: "file-loader",
options: {
name: "[name].[contenthash].[ext]",
outputPath: "fonts/",
},
},
],
},
{
test: /\.svg$/,
use: [
{
loader: "svg-url-loader",
options: {
limit: 10000,
},
},
],
},
],
},
devServer: {
contentBase: path.join(__dirname, "build"),
historyApiFallback: true,
overlay: true,
},
plugins: [
new HtmlWebpackPlugin({
title: "esBUild",
template: "src/index.html",
}),
new CopyWebpackPlugin({
patterns: [{ from: "assets", to: "assets" }],
}),
new webpack.ProvidePlugin({
process: "process/browser",
Buffer: ["buffer", "Buffer"],
React: "react",
}),
],
};
export default config;
here is tsconfig.json:
{
"compilerOptions": {
// The standard typing to be included in the type checking process.
"lib": ["dom", "dom.iterable", "esnext"],
// Whether to allow JavaScript files to be compiled.
"allowJs": true,
//This allows default imports from modules with no default export in the type checking process.
"allowSyntheticDefaultImports": true,
// Whether to skip type checking of all the type declaration files (*.d.ts).
"skipLibCheck": true,
// This enables compatibility with Babel.
"esModuleInterop": true,
"strict": true,
// Ensures that the casing of referenced file names is consistent during the type checking process.
"forceConsistentCasingInFileNames": true,
// This allows modules to be in .json files which are useful for configuration files.
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"module": "es6",
"target": "es5",
"sourceMap": true,
"noEmit": true,
"jsx": "react",
"baseUrl": "src",
"paths": {
"components": ["components/*"]
}
},
"include": ["src"]
}
THis is the error I get :
import path from "path";
^^^^^^
SyntaxError: Cannot use import statement outside a module
I googled it and see some people suggest adding "type":"module", it did not work.
in tsconfig.json
"module": "es6" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
I tried each option but this did not work neither.
If I discard the typescript configuration, set up webpack with common.js, it works
Also .babelrc
{
"presets": [
"#babel/preset-react",
"#babel/preset-env",
"#babel/preset-typescript"
],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-object-rest-spread"
]
}
In my case I have to change to "module": "commonjs", inside tsconfig.json. Refer https://www.typescriptlang.org/tsconfig#module
In my case I have to install typescript types of plugins (vscode suggested it after restart the ide).
For example:
For dotenv-webpack package, I installed #types/dotenv-webpack.
Please refer to this section of the Webpack configuration documentation:
The above sample assumes version >= 2.7 or newer of TypeScript is used with the new esModuleInterop and allowSyntheticDefaultImports compiler options in your tsconfig.json file.
Note that you'll also need to check your tsconfig.json file. If the module in compilerOptions in tsconfig.json is commonjs, the setting is complete, else webpack will fail with an error. This occurs because ts-node does not support any module syntax other than commonjs.
There are three solutions to this issue:
Modify tsconfig.json.
Modify tsconfig.json and add settings for ts-node.
Install tsconfig-paths.
You've set the correct values for "esModuleInterop" and "allowSyntheticDefaultImports" in your tsconfig.json, so, to get rid of the error, you should do one of the above three options.
The first one suggests you to change the "module" compiler option's value to "commonjs".
The second one allows you to keep the "module" option's value as is, but you should add the settings for ts-node in your tsconfig.json.
The third one requires additional package installation and a separate TS configuration file.
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 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)