Webpack build fail when adding a specific external lib - node.js

It happens on a build for server side, i am already using a lot of external modules and everything worked great until now.
I am trying to add the module auth0-js and the error happens when i add the import on this lib var crypto = require('crypto'); TypeError: require is not a function.
Here is my webpack config (for server side):
const path = require('path');
const webpack = require('webpack');
const StatsPlugin = require('stats-webpack-plugin');
module.exports = {
entry: './handler.js',
target: 'node',
profile: false,
output: {
path: path.resolve(__dirname, '../dist-server'),
publicPath: '/',
filename: 'handler.js',
libraryTarget: 'commonjs'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
include: path.resolve(__dirname, '..'),
use: 'babel-loader'
},
{
test: /\.pug$/,
use: 'pug-loader'
}
]
},
plugins: [
new webpack.DefinePlugin({
__CLIENT__: false,
__SERVER__: true
}),
new StatsPlugin('stats.json', {
chunkModules: true,
exclude: [/node_modules[\\\/]react/]
})
],
resolve: {
modules: [
path.resolve('./src'),
path.resolve('./node_modules')
]
},
devtool: 'source-map'
};
My .babelrc file is:
{
"presets": [
"react",
"latest"
],
"plugins": [
"transform-object-rest-spread",
"transform-runtime"
]
}
I tried to remove the exclude node_modules but i get other errors.
I am curious to know how a single library can break everything, what should i do?

Related

importing react-virtuoso throws error "You may need an appropriate loader to handle this file type."

My project works fine but after installing and importing react-virtuoso it throws error.
ERROR in ./~/react-virtuoso/dist/index.mjs
Module parse failed: C:\Users\Rocky\Documents\betterdash\node_modules\react-virtuoso\dist\index.mjs Unexpected token (364:22)
You may need an appropriate loader to handle this file type.
| }
| const Component = forwardRef((propsWithChildren, ref) => {
| const { children, ...props } = propsWithChildren;
| const [system2] = useState(() => {
| return tap(init(systemSpec), (system22) => applyPropsToSystem(system22, props));
# ./src/components/order-viewer.jsx 13:21-46
# ./src/main.js
# multi whatwg-fetch ./src/main.js
Here is my webpack.config.js
const path = require("path");
const webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: ["whatwg-fetch", "./src/main.js"],
output: {
path: path.join(__dirname, "dist"),
filename: "bundle.js",
publicPath: "/",
},
module: {
loaders: [
{
test: /.jsx?$/,
loader: "babel-loader",
include: path.join(__dirname, "src"),
exclude: /node_modules/,
query: {
presets: ["es2015", "react", "flow"],
plugins: ["transform-flow-strip-types"],
},
},
{
test: /\.s?css$/,
loaders: ExtractTextPlugin.extract({
use: ["css-loader", "sass-loader"],
fallback: "style-loader",
}),
},
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new ExtractTextPlugin({
filename: "style.css",
allChunks: true,
disable: process.env.NODE_ENV === "development",
}),
],
devtool: "source-map",
};
I tried deleting node_modules then run npm install but it doesn't solve the problem. If I remove the part of code that imports the react-virtuoso the error also gone.
import { Virtuoso } from "react-virtuoso";
I had the same problem with Jest and I noticed they have renamed the index.js file to index.cjs from version 4.0.0 to version 4.0. I would assume you have to do something similar with Webpack.
transform: {
'^.+\\.(cjs|js|jsx)$': [
'babel-jest',
{ configFile: './babel.config.js' }
]
},
If you install V4.0.0 it will work if that is the same issue.

How do I ignore a an import in webpack?

I have a webpack file that looks like the one below, and I have a line in my handler.ts which looks like this:
import { PayoutEntity, IPayout, payoutEntityManager } from "/opt/nodejs/orm";
However I get the following error as the module/path for "/opt/nodejs/orm" doesn't exist locally:
Module not found: Error: Can't resolve '/opt/nodejs/orm'
The webpack build is for a lambda and the files for "/opt/nodejs/orm" are in a lambda layer that will only be accessable from the application once it's deployed to aws.
So in fact I would like webpack to ignore completely /opt/nodejs/orm and not even try to pack it.
I've tried using the ignore plugin with const ignore = new webpack.IgnorePlugin({resourceRegExp:/^(\/opt\/nodejs\/search|\/opt\/nodejs\/orm|\/opt\/nodejs\/put-event)$/}) but this just results in baking the "module not found" error into the bundled output file.
"use strict";
const path = require("path");
module.exports = {
devtool: "source-map",
entry: "./src/handler.ts",
mode: "production",
target: "node",
externals: [nodeExternals()],
node: {
__dirname: true,
},
output: {
filename: "index.js",
libraryTarget: "commonjs2",
path: path.resolve(__dirname, ".build"),
},
module: {
rules: [
{
test: /\.(graphql|gql)$/,
loader: "graphql-tag/loader",
exclude: /node_modules/,
},
{
test: /\.(tsx?)$/,
loader: "ts-loader",
exclude: [
[
path.resolve(__dirname, "node_modules"),
path.resolve(__dirname, ".serverless"),
path.resolve(__dirname, ".webpack")
],
],
options: {
transpileOnly: false,
experimentalWatchApi: true,
},
},
],
},
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
};

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted - NodeJS, Express & Webpack

I am developing a web application using Node.js, Express & Webpack. Everything was going well until Webpack was upgraded to Webpack 5 and lots of bugs appeared. I have managed to solve all the errors but there is a warning I can't solve. I have seen this post but it's related to Angular so I don't think it helps me much: Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
WARNING in ./node_modules/terser-webpack-plugin/dist/minify.js
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
This is my webpack.config.js; resolve fields and node-polyfill-webpack-plugin are used to solve Webpack 5 bugs and errors.
const path = require("path")
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")
const webpack = require('webpack')
const HtmlWebPackPlugin = require("html-webpack-plugin")
module.exports = {
resolve:{
fallback: {
"fs": false,
"path": false,
"worker_threads":false,
"child_process":false,
"http": false,
"https": false,
"stream": false,
"crypto": false,
}
},
entry: {
main: './src/js/main.js',
index:'./src/js/'
},
output: {
path: path.join(__dirname, 'dist'),
//publicPath: '/',
filename: '[name].js'
},
mode:"development",
target: 'web',
devtool: 'source-map',
module: {
rules: [
{
test: /\.(png|jp(e*)g|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]'
}
}]
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
test: /\.bpmn$/,
use: 'raw-loader'
},
{
// Loads the javacript into html template provided.
// Entry point is set below in HtmlWebPackPlugin in Plugins
test: /\.html$/,
use: [
{
loader: "html-loader",
//options: { minimize: true }
}
]
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: '!!raw-loader!./src/views/pages/index.ejs',
filename: "./index.ejs",
excludeChunks: [ 'server', 'main' ]
}),
new HtmlWebPackPlugin({
template: '!!raw-loader!./src/views/pages/bmv.ejs',
filename: "./bmv.ejs",
excludeChunks: [ 'server', 'index' ]
}),
new webpack.NoEmitOnErrorsPlugin(),
new NodePolyfillPlugin()
]
}
configure the webpack:
const path = require('path');
module.exports = {
//...
resolve: {
alias: {
'terser-webpack-plugin': path.resolve(__dirname, 'node_modules/terser-webpack-plugin/dist/minify.js'),
},
},
};

Issue with #babel import _Object$defineProperty from "../../core-js/object/define-property";

I am trying to configurate my NodeJs project. If I add any async/await in the code, the following error appears:
1] import _Object$defineProperty from "../../core-js/object/define-property";
[1] ^^^^^^^^^^^^^^^^^^^^^^
[1]
[1] SyntaxError: Unexpected identifier
My .babelrc:
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": true
},
}
]
],
"plugins": ["#babel/plugin-transform-regenerator"]
}
My webpack.config.js is
const path = require("path")
const nodeExternals = require("webpack-node-externals")
const config = {
entry: "./src/index.js",
target: "node",
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
output: {
filename: "[name].js",
publicPath: "/client/dist/",
chunkFilename: "[name].bundle.js",
path: `${__dirname}/client/dist`
},
module: {
rules: [
{
test: /\.(js)$/,
exclude: ["node_modules/"],
include: [/src/],
use: {
loader: "babel-loader"
},
plugins: ["#babel/plugin-transform-runtime"]
},
{
test: /\.(woff2?|eot|ttf|otf)$/,
loader: "file-loader",
options: {
limit: 10000,
name: "[name].[hash:7].[ext]"
}
}
]
},
watch: true
}
module.exports = config
I tried to add #babel/plugin-transform-runtime, but it did not solve my problem.
Could somebody give me the clue, what I am doing not right?
Thanks in advance
Try adding babel-polyfill to your project, and as an entry for webpack:
yarn add babel-polyfill -D
and in webpack.config.js:
const path = require("path")
const nodeExternals = require("webpack-node-externals")
const config = {
entry: {
polyfill: "babel-polyfill",
app: "./src/index.js"
},
...

TypeScript typings broken (error TS2687): All declarations of 'iterator' must have identical modifiers

I'm having an issue getting my typings correctly after I've added the router package to my Angular application (which required an upgrade of Core, Common, Compiler etc.).
Googling ob that specific error code led me to a number of problems, the main resolution for which is removing node_modules and typings and recreating them. I've done so but experience the same misbehavior.
On SO, there's another question but it's old, relates to a different versions of most of the packages and I hardly see how it relates to my problem.
Frankly, I'm a bit lost because I have no idea how to troubleshoot it at all. Below is my tsconfig.json if it helps to spot something odd.
edit
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const distribution = path.resolve(__dirname, "distribution");
const application = path.resolve(__dirname, "source/application");
const resources = path.resolve(__dirname, "source/resources");
module.exports = {
entry: "./source/application/main.ts",
output: {
path: distribution,
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.png$/, loader: "raw-loader", include: [resources] },
{ test: /\.s(a|c)ss$/, loaders: ["raw-loader", "sass-loader"] },
{ test: /\.html$/, loader: "raw-loader", include: [application] },
{ test: /\.ts$/, loader: "ts-loader", include: [application] },
]
},
resolve: {
modules: ["node_modules", application],
extensions: [".js", ".ts"]
},
performance: {},
devtool: "source-map",
context: __dirname,
target: "web",
externals: [],
stats: {},
devServer: {
contentBase: distribution,
port: 3002
},
plugins: [
new HtmlWebpackPlugin({ template: "./source/index.html" }),
new CopyWebpackPlugin([{ from: "./source/resources", to: "resources" }])
]
}
In Webpack.common.js remove the line debug=true, and change the below code
module.exports = {
entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
},
resolve: {
extensions: ['*', '.js', '.ts']
},
module: {
rules: [
]},
plugins: [
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
helpers.root('./src'), // location of your src
{} // a map of your routes
),
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),

Resources