webpack 5 Error "Can't resolve 'uglify-js', '#swc/core', 'esbuild' - node.js

I have some errors with webpack 5, express, github actions.
I use the github actions because want to use github secrets.
also, I use webpack because of using the secrets in the code.
anyway, I got errors below,
ERROR in ./node_modules/terser-webpack-plugin/dist/utils.js 479:6-26
Module not found: Error: Can't resolve 'uglify-js' in '/Users/luna/workspace/express_api/node_modules/terser-webpack-plugin/dist'
# ./node_modules/terser-webpack-plugin/dist/index.js 27:4-22
# ./webpack.config.js 2:21-53
# ./app.js 13:15-45
ERROR in ./node_modules/terser-webpack-plugin/dist/utils.js 557:14-34
Module not found: Error: Can't resolve '#swc/core' in '/Users/luna/workspace/express_api/node_modules/terser-webpack-plugin/dist'
# ./node_modules/terser-webpack-plugin/dist/index.js 27:4-22
# ./webpack.config.js 2:21-53
# ./app.js 13:15-45
ERROR in ./node_modules/terser-webpack-plugin/dist/utils.js 635:18-36
Module not found: Error: Can't resolve 'esbuild' in '/Users/luna/workspace/express_api/node_modules/terser-webpack-plugin/dist'
# ./node_modules/terser-webpack-plugin/dist/index.js 27:4-22
# ./webpack.config.js 2:21-53
# ./app.js 13:15-45
Also, got 15 warnings. if you want to the warnings, let me know.
what is the problem?
Below is the webpack.config.js
const webpack = require("webpack");
module.exports = {
target: "async-node",
mode: "production",
entry: "./app.js",
output: {
path: "/dist",
filename: "main.js",
},
plugins: [
new webpack.DefinePlugin({
"process.env.PA_URL": JSON.stringify(process.env.PA_URL),
"process.env.PA5_EMAIL": JSON.stringify(process.env.PA5_EMAIL),
"process.env.PA5_PASSWORD": JSON.stringify(process.env.PA5_PASSWORD),
}),
],
};
the webpack version is wrong?

You are bundling your entry file, but also any node_modules your ./app.js requires, which in turn tries to require a bunch of third-party stuff, which is not available - hence the errors on missing modules.
Exclude those node_modules by extending your webpack config:
yarn add -D webpack-node-externals
(see: https://www.npmjs.com/package/webpack-node-externals)
const webpack = require("webpack");
const nodeExternals = require("webpack-node-externals");
module.exports = {
target: "async-node",
mode: "production",
entry: "./app.js",
externalsPresets: { node: true }, // <-- here
externals: [nodeExternals()], // <-- and here
...etc
That should exclude them and you should be good to go.

Related

Couldn't import web3 library in react application

ERROR in ./node_modules/cipher-base/index.js 3:16-43
Module not found: Error: Can't resolve 'stream' in 'C:\Users\Sumana\Desktop\Web3\web3app\node_modules\cipher-base'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }
You can fix this issue in 2 way .
Delete node_module then change your react-scripts version from "5.0.0" to "4.0.3" after that run npm install.
or
Configure webpack.
1 - install these packages .
npm install fs assert https-browserify os os-browserify stream-browserify stream-http react-app-rewired
2 - Create config-coverrides.js in Root dir of your project next to the package.json
const webpack = require('webpack');
module.exports = function override(config, env) {
config.resolve.fallback = {
url: require.resolve('url'),
fs: require.resolve('fs'),
assert: require.resolve('assert'),
crypto: require.resolve('crypto-browserify'),
http: require.resolve('stream-http'),
https: require.resolve('https-browserify'),
os: require.resolve('os-browserify/browser'),
buffer: require.resolve('buffer'),
stream: require.resolve('stream-browserify'),
};
config.plugins.push(
new webpack.ProvidePlugin({
process: 'process/browser',
Buffer: ['buffer', 'Buffer'],
}),
);
return config;
}
I have had this issue for the last week too. It has been documented in many place like this. I don't understand how to fix it but it seems like the people who made the library will fix it https://github.com/ChainSafe/web3.js/issues/4659
Install the polyfills for node.JS and adding two things to webpack.config.js:
npm install node-polyfill-webpack-plugin
In the file [node_modules > react-scripts > config > webpack.config.js] add:
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
module.exports > return > plugins:
plugins: [
new NodePolyfillPlugin(),
……………
]
More on the solution:
https://github.com/Richienb/node-polyfill-webpack-plugin#readme

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default

I'm trying to use Socket.io in my Laravel/Vue.js app. But I'm getting this error when running npm run dev.
Module not found: Error: Can't resolve 'path' in '/home/nicolas/LaravelProjects/Chess/node_modules/socket.io/dist'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "path": false }
webpack compiled with 9 errors
I tried changing the webpack.config.js file by adding resolve.fallback: { "path": false }, but it doesn't seem to help. It is possible that I'm doing it wrong since I have 4 webpack.config.js files in my project (I don't know why).
Maybe can I downgrade webpack? Thanks!
This fix worked for me (Vue 3):
In vue.config.js, add:
const { defineConfig } = require('#vue/cli-service')
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")
module.exports = defineConfig({
transpileDependencies: true,
configureWebpack: {
plugins: [
new NodePolyfillPlugin()
]
}
})
Followed by npm install node-polyfill-webpack-plugin
I had this problem in ReactJS with create-react-app(facebook) but other packages (crypto-browserify)
Solution:
First install the necessary packages in this problem "path-browserify" but in my case "crypto-browserify"
Modify webpack.config.js in reactjs with create-react-app this file is inside:
node_modules/react-scripts/config/webpack.config.js
Search module.exports and inside this function there is a return:
module.exports = function (webpackEnv) {
...
return {
...
resolve: {
...
fallback: {
// Here paste
path: require.resolve("path-browserify"),
// But in mi case I paste
crypto: require.resolve("crypto-browserify"),
}
}
}
}
Note: This solution works, but when the webpack project starts it shows warnings
Pd: I am not native speaker English, but I hope understand me.
I have the same issue in React (feb-2022) using Real (realm-web) from Mongo.
I solve this in two steps:
npm i stream-browserify crypto-browserify
create fallback object into webpack.config.js at node_modules/react-scripts/config/webpack.config.js
module.exports = function (webpackEnv) {
...
return {
...
resolve: {
...
fallback: { // not present by default
"crypto": false,
"stream": false
}
}
}
I have the same issue with crypto. Some say that adding a proper path in TS config (and installing a polyfill) should resolve the issue.
tsconfig.json
{
"compilerOptions": {
"paths": {
"crypto": [
"./node_modules/crypto-browserify"
],
}
Details https://github.com/angular/angular-cli/issues/20819
I'm still fighting with crypto, but above link might help in your struggles.
I had the same issue, Strangely an import {script} from 'laravel-mix' in my app.js. I removed it and everything went back to normal.
I could not get the other answers to work with React on a new project with rss-parser. The error messages aren't clear. I fixed it by adding this line to the webpack configuration:
resolve: {
extensions: ['.tsx', '.ts', '.js'],
fallback: { "http": false, "browser": false, "https": false,
"stream": false, "url": false, "buffer": false, "timers": false
}
},
Watch out for this import in your app.js. Removing it fixed my issue.
use the version of webpack 4.46.0 to remove the error
I had to delete this line in a Vue component to solve the problem:
import { ContextReplacementPlugin } from "webpack";
If you use create-react-app(cra)
You have to overwrite the default webpack file
to do that you need to install a package like "react-app-rewired" that
will help overwriting and merge your configuration with the ones were
added by react scripts
First
npm install --D react-app-rewired
create a new file in the root directory called "config-overrides.js"
Install(using npm) and Add the required dependencies to the created config file
npm i -D path-browserify
install other packages as the error message shows
const webpack = require('webpack');
module.exports = function override(config) {
const fallback = config.resolve.fallback || {};
Object.assign(fallback, {
path: require.resolve('path-browserify'),
add others as shown in the error if there are more
});
config.resolve.fallback = fallback;
config.plugins = (config.plugins || []).concat([
new webpack.ProvidePlugin({
process: 'process/browser',
Buffer: ['buffer', 'Buffer'],
}),
]);
return config;
};
Update your package.json scripts
"scripts": {
"build": "react-app-rewired build",
....
"start": "react-app-rewired start",
"test": "react-app-rewired test"
},
Also please note that a new version of react-scripts(newer than 5.0.1) might solve the issue.
had this issue in a react-app.
installation of stream-browserify crypto-browserify didn't work for me
went through with hjpithadia's answer in Reactjs with a slight change in webpack.config.js
install the package
npm install node-polyfill-webpack-plugin
find the webpack configuration file here
node_modules/react-scripts/config/webpack.config.js
import the package
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
search for module.exports
in plugin array add this new NodePolyfillPlugin(),
module.exports = function (webpackEnv) {
...
return {
...
plugins: [
new NodePolyfillPlugin(),
...
]
}
}
For React apps, if you don't need the module make sure webpack ignores it.
install craco https://craco.js.org/docs/getting-started/
create a craco.config.js in the root of your project, mine looks like this:
module.exports = {
webpack: {
configure: (webpackConfig) => {
webpackConfig.resolve.fallback = webpackConfig.resolve.fallback || {}
webpackConfig.resolve.fallback.zlib = false
webpackConfig.resolve.fallback.http = false
webpackConfig.resolve.fallback.https = false
webpackConfig.resolve.fallback.stream = false
webpackConfig.resolve.fallback.util = false
webpackConfig.resolve.fallback.crypto = false
return webpackConfig;
},
}
};
I resolved similar issue:
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }
Installing the npm i stream-browserify --save-dev
Making the custom webpack.config.js file containing:
module.exports = {
resolve: {
fallback: { stream: require.resolve("stream-browserify") },
},
};
Installing the npm install #angular-builders/custom-webpack --save-dev
Assigning (angular.json: projects -> <proj_name> -> architect -> build -> options)
"customWebpackConfig": {
"path": "./webpack.config.js"
}
Changing the: build / serve / extract-i18n / test – as of your needs – to use custom Webpack config:
"builder": "#angular-builders/custom-webpack:browser",
I finally found the solution. With laravel, you have to change the webpack.mix.js file and not webpack.config.js.

How to: 1 Webpack for all project with importing lib from node_modules

// Project Tree View: My idea about using Webpack.
+ Toolkit:
- D:/Toolkit/Webpack/webpack.config.js
+ Project:
- D:/Project/A/build/index.ts
- D:/Project/B/build/index.ts
- D:/Project/C/build/index.ts
// Toolkit: [webpack.config.js] file
const path = require('path');
module.exports = (env) => {
let project_root = env.path;
console.log(env);
console.log(__dirname);
return {
mode: env.mode,
entry: project_root+'/build/index.ts',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
include: [
path.resolve(project_root, 'build'),
path.resolve('./node_modules'),
]
}, {
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
"sass-loader",
]
}
]
},
output: {
publicPath: 'public',
filename: 'script.js',
path: path.resolve(project_root, 'assets/js')
},
resolve: {
modules: ['node_modules'],
},
}
}
Build command: yarn build --env=path=D:/Project/C
The command works without error, but when importing any library from the node_modules
Ex:
import {lib} from "example_lib";
import {lib} from "~example_lib";
import {lib} from "#example_lib";
import {lib} from "node_modules/example_lib";
import {lib} from "./node_modules/example_lib";
The Error
ERROR in ../A/build/index.ts 1:0-52
Module not found: Error: Can't resolve 'example_lib' in 'D:\Project\A'
resolve 'example_lib' in 'D:\Project\A'
Parsed request is a module
No description file found in D:\Project\A\build or above
resolve as module
D:\Project\A\build\node_modules doesn't exist or is not a directory
...
D:\node_modules doesn't exist or is not a directory
ERROR in D:\Project\A\build\index.ts
../A/build/index.ts 1:20-49
[tsl] ERROR in D:\Project\A\build\index.ts(1,21)
TS2792: Cannot find module 'example_lib'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?
webpack 5.26.2 compiled with 2 errors in 1939 ms
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
The Question is:
How to use ONLY 1 Webpack node_modules for all projects ?
Gulp can resolve this issue but how about Webpack ?
I do not want every project to have 1 node_modules or webpack, package,... inside (it trash my PC !)
The issue has been resolved !
The above code is correct.
Format ".js" works normally; however ".ts" need to add // #ts-ignore above every import external node_modules.
This is the answer !
// #ts-ignore
import {lib} from "example_lib";
NOTE: 7 days researching Webpack
This is my opinions:
Gulp is much more than Webpack even it has lower user
These are the Pros about Gulp that Webpack should have !
Less time for controlling the core.
User-friendly.
Clear and Clean Structure, less bracket.
Easy and Flexible for creating the custom config.
Easy to use, develop through time.
Not just for web field, on the backup data, auto,... as well.
1 node_modules for all external projects (Gulp less bug and coding line than Webpack).
Compile time are the same.
👉🏾 Gulp is the King 👑 !

Unable to implement webpack in project with node-red

I am trying to implement webpack in my project which contains node-red. However, I keep getting the following warning. Please suggest how to solve this error -
WARNING in ./node_modules/node-red/red/runtime/storage/localfilesystem/projects/git/node-red-ask-pass.sh 1:26
Module parse failed: Unexpected token (1:26)
You may need an appropriate loader to handle this file type.
> "$NODE_RED_GIT_NODE_PATH" "$NODE_RED_GIT_ASKPASS_PATH" "$NODE_RED_GIT_SOCK_PATH" $#
|
# ./node_modules/node-red/red/runtime/storage sync ^\.\/.*$ ./localfilesystem/projects/git/node-red-ask-pass.sh
# ./node_modules/node-red/red/runtime/storage/index.js
# ./node_modules/node-red/red/runtime/index.js
# ./app.js
My webpack.config.js is -
const path = require('path');
var nodeExternals = require('webpack-node-externals');
module.exports = {
target: 'node',
externals: [nodeExternals()],
entry: './app.js',
output: {
path: path.resolve(__dirname, './output'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js','.json', '.sh'],
modules: [
'node_modules'
],
},
module: {
rules: [
{
test:/\.css$/,
use:['style-loader','css-loader']
},
{
test: /\.coffee$/,
use: [ 'coffee-loader' ]
}
]
}
};
For Webpack, every file is a .js. In order to handle other extensions, like .css or .sh, you're supposed to use a loader, like you did with css-loader, that will tranform CSS rules into JS.
The issue you're facing is that you've got an import chain (./app.js -> .../index.js -> .../index.js -> .../node-red-ask-pass.sh), so Webpack will, at some point, will import a .sh file, but will throw an error because shell code is obviousouly invalid JavaScript. that is why you're seeing the error that you have.
By the way, I couldn't reproduce the issue you're facing:
npm init -y
npm i node-red
# ./node_modules/node-red/red is not a directory
So it was probably a node-red bug. Update the package to the latest version.

Building ReactJS Project with Webpack causes graceful-js to report error "can't resolve 'fs'"

I was building my project last night. It's a Node project building React distributable frontend code with webpack. When I was done, I shut down my computer. I turned on my computer this morning and now, with no code or config changes to my knowledge, I get errors that some kind of dependency of a dependency is missing.
ERROR in ./~/fsevents/~/graceful-fs/fs.js
Module not found: Error: Can't resolve 'fs' in '/Users/stevenkitzes/Documents/Career Dev/C2 to A1/react-lnl/demo/react-lnl/node_modules/fsevents/node_modules/graceful-fs'
# ./~/fsevents/~/graceful-fs/fs.js 3:9-22
# ./~/fsevents/~/graceful-fs/graceful-fs.js
# ./~/fsevents/~/fstream/lib/reader.js
# ./~/fsevents/~/fstream/fstream.js
# ./~/fsevents/~/tar-pack/index.js
# ./~/fsevents/~/node-pre-gyp/lib/package.js
# ./~/fsevents/~/node-pre-gyp/lib ^\.\/.*$
# ./~/fsevents/~/node-pre-gyp/lib/node-pre-gyp.js
# ./~/fsevents/fsevents.js
# ./~/chokidar/lib/fsevents-handler.js
# ./~/chokidar/index.js
# ./~/watchpack/lib/DirectoryWatcher.js
# ./~/watchpack/lib/watcherManager.js
# ./~/watchpack/lib/watchpack.js
# (webpack)/lib/node/NodeWatchFileSystem.js
# (webpack)/lib ^.*$
# (webpack)/lib/webpack.js
# ./jsx-map/jsx-build.js
Here is my webpack config file:
var webpack = require('webpack');
var path = require('path');
var APP_DIR = path.resolve(__dirname, '.');
var plugins = [];
var config = {
entry: APP_DIR + '/jsx.js',
output: {
path: APP_DIR,
filename: 'jsx-out.js'
},
module: {
loaders: [
{
test: /\.jsx?/,
exclude: /node_modules/,
include: APP_DIR,
loader: 'babel-loader',
query: {
presets: ['react']
}
}
]
},
plugins: plugins
};
module.exports = config;
It sounds like you may be trying to bundle both server-side (node) and client-side (react stuff) with webpack. If so you need to bundle them separately to create 2 different bundle files.
One for node for your to exeucte e.g., node bundle-server.js (assuming your server-side bundle is generated as 'bundle-server.js')
Another for inclusion into your front-end html code, e.g., <script src='./bundle-client.js'></script> (assuming your client-side bundle is generated as 'bundle-client.js').
Specifically you need to set options in your webpack config file to have two 'output' and two 'target', one for server-side, and another for client-side.
For details on doing client-side and server-side bundling with webpack, you can refer to https://medium.com/code-oil/webpack-javascript-bundling-for-both-front-end-and-back-end-b95f1b429810

Resources