Module not found: Error: Can't resolve 'babel-loader' - node.js

Just I did my web pack upgrade from 2.x to 4.x. By doing npm install i was getting the following error
Module not found: Error: Can't resolve 'babel-loader'
Following the github thread , i added the following lines in webpack.config.json
resolveLoader: { root: path.join(__dirname, 'node_modules') }
But i got the following error ,
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.resolveLoader has an unknown property 'modulesDirectories'. These properties are valid: object { alias?, aliasFields?, cachePredicate?, descriptionFiles?, enforceExtension?, enforceModuleExtension?, extensions?, fileSystem?, mainFields?, mainFiles?, moduleExtensions?, modules?, plugins?, resolver?, symlinks?, unsafeCache?, useSyncFileSystemCalls? }
babel-loader version is 7.1.4 . Webpack upgrade has introduced this error. Any suggestions on this?

Just install the module:
npm install babel-loader
or
yarn add babel-loader
I got this problem fixed by running the above command.

Aren't you install this "babel-loader"
https://www.npmjs.com/package/babel-loader
module: {
rules: [{
test: /\.jsx?$/,
include: [
path.resolve(__dirname, 'src/js'),
],
loader: "babel-loader",
options: {
presets: ["es2015"],
plugins: [
["babel-plugin-root-import", {
"rootPathSuffix": "src/js"
}],
[
"transform-runtime", {
"helpers": false,
"polyfill": false,
"regenerator": true,
"moduleName": "babel-runtime"
}
],
"transform-object-assign", "transform-function-bind"
]
},
// options for the loader
}}

Related

How to transpile npm module with "optional chaining" code to earlier version of node?

Currently I am running node v16.13.1 and I wrote small npm package I would like to publish to npm and then install globally and run as executable.
Application works fine when built with current version but because I am using "optional chaining" (object?.something) it does not work with node 12.
I do not want to change code, but I would like to transpile it so it runs it in all node versions between 12 and 16+.
My webpack look like this:
const path = require("path");
const webpack = require("webpack");
module.exports = (env, argv) => {
console.log('Log::', env, argv);
const config = {
entry: './src/index.js',
devtool: (argv.mode === 'development') ? 'cheap-module-source-map' : undefined,
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js',
},
experiments: {
outputModule: true,
},
plugins: [
//empty pluggins array
new webpack.BannerPlugin({ banner: "#!/usr/bin/env node", raw: true }),
],
module: {
// https://webpack.js.org/loaders/babel-loader/#root
rules: [
{
test: /.m?js$/,
loader: 'babel-loader',
exclude: /node_modules/,
}
],
},
resolve: {
fallback: {
"fs": false,
"path": false,
"os": false,
assert: require.resolve('assert'),
path: require.resolve('path-browserify'),
util: require.resolve('util'),
},
},
target: "node12.22"
};
console.log('Log::', config);
return config;
}
and this is .babelrc
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"esmodules": true
}
}
]
]
}
running npm build with target: "node" gives following error:
Error: For the selected environment is no default ESM chunk format available:
ESM exports can be chosen when 'import()' is available.
running it with target: "node12.22" does not give any errors but when I try to run I get:
SyntaxError: Cannot use import statement outside a module
←[90m at Object.compileFunction (node:vm:352:18)←[39m
If I remove target:"node" all together I am getting following error when run:
TypeError: s.existsSync is not a function
If I run it without fallback: { "fs": false then I get compile errors:
Module not found: Error: Can't resolve 'fs' in
Try adding the following to your Webpack config to have the optimizer output code that's compatible with ECMA 6, which does not include optional chaining:
optimization: {
minimizer: [
new TerserPlugin({
terserOptions: {
ecma: 6,
mangle: false,
// compress: false, // NOTE: Not certain you can just pass false here, but I think probably
},
}),
],
},
And be sure to install the TerserJS Plugin and require it in your config, const TerserPlugin = require('terser-webpack-plugin');

Webpack 5 webpackMissingModule error for node_modules package

I've been working on upgrading a repository from Webpack version 4 to 5, and I've encountered a very strange problem where Webpack will throw an error at runtime telling me that a package in node_modules could not include a specific "module" (referring to a subdirectory of that package). The module in question is #hapi/joi, and the error I'm receiving is:
Error: Cannot find module './types/alternatives'
At one point it was telling me that the error related to that package, but now it just throws the error with no package context. I've dug into the #hapi/joi package, and I can see this set of imports in the index.js:
const internals = {
alternatives: require('./types/alternatives'),
array: require('./types/array'),
boolean: require('./types/boolean'),
binary: require('./types/binary'),
date: require('./types/date'),
func: require('./types/func'),
number: require('./types/number'),
object: require('./types/object'),
string: require('./types/string'),
symbol: require('./types/symbol')
};
I've verified that the ./types/alternatives directory exists and that it has an index.js of its own. This package also works fine on Webpack 4. I tried upgrading to the standalone joi package, and it threw the same error.
I'm pretty confused at to why this error is throw at runtime. I would think this would be a build error, though maybe it has something to do with building the target for node?
This is my Webpack config. It's mostly unmodified from v4:
{
entry: {
adviceServer: "./src/server/index.ts",
},
target: "node",
bail: true,
mode: env.NODE_ENV,
output: {
path: path.resolve(root, "dist", "js"),
filename: `[name].${env.ASSET_HASH}.js`
},
module: {
rules: [
{
test: /\.tsx?$/,
use: [
{
loader: "ts-loader",
options: {
context: path.resolve(root, "src"),
configFile: tsconfigPath,
transpileOnly: false
}
}
],
exclude: [
"/node_modules",
"/**/*.test.ts/"
]
},
{
test: /\.s?css$/,
use: ["isomorphic-style-loader", "css-loader", "sass-loader"]
}
]
},
resolve: {
extensions: [".tsx", ".ts", ".js", ".jsx", "scss", ".json"],
alias: {
styles: path.resolve(root, "src", "scss"),
canvas: path.resolve(root, "src", "etc", "fileMock"),
ws: path.resolve(root, "src", "etc", "fileMock")
},
plugins: [
new TsconfigPathsPlugin({
configFile: tsconfigPath
})
]
},
devtool: "eval-cheap-source-map",
plugins: [
new BundleTracker({ filename: "./webpack-stats.json" })
]
}
I had a similar issue upgrading from webpack 4 but with a different external library. In my case it was caused by two webpack#5 versions installed at the same time. Check your package-lock.json/yarn.lock and add overrides/resolutions to your package.json if there are several versions. If not — try removing your node_modules folder and installing packages again.

Why can't I resolve nodejs default modules when using preset-env node?

I am writing a plugin for an app that runs Chromium Embedded Framework (CEF) with an older version of Node.
I threw webpack & babel into the app. When I run webpack, it fails on a file that has const fs = require('fs');, or any other default node package. This is happening both for my code and dependencies:
Module not found: Error: Can't resolve 'fs' in '/Users/me/repositories/myrepo/node_modules/chokidar'
My .babelrc is the following:
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": true
}
}
]
]
}
My webpack config is essentially:
module.exports = {
entry: './src/main.jsx',
mode: process.env.NODE_ENV,
devtool: isDev ? 'eval-source-map' : false,
output: {
path: PLUGINDIR,
filename: 'main.js',
libraryTarget: 'umd'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
plugins: ['transform-react-jsx']
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
resolve: {
extensions: ['.js', '.jsx', '.css']
}
};
webpack config also needs target: 'node'. Doing it just in .babelrc was not enough.

Can't resolve 'babel-loader'

I am trying to configure my first node react app.
I keep getting an error that says "Can't resolve babel-loader".
Googling that error, I found a couple of suggestions which do not work.
The first is to add the following to my webpack.config.js
// resolveLoader: {
// modulesDirectories: '/usr/local/lib/node_modules'
// },
Trying that produces an error that says:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.resolveLoader has an unknown property 'modulesDirectories'. These properties are valid:
object { alias?, aliasFields?, cachePredicate?, descriptionFiles?, enforceExtension?, enforceModuleExtension?, extensions?, fileSystem?, mainFields?, mainFiles?, moduleExtensions?, modules?, plugins?, resolver?, symlinks?, unsafeCache?, useSyncFileSystemCalls? }
The next suggestion is to try:
resolveLoader: {
fallback: '/usr/local/lib/node_modules'
},
That produces a similar error.
Does anyone have any advice on how to get started with this configuration. Understanding the documentation is proving difficult - every second word is jargon and I can't find a reference point to find fundamental understanding of what needs to be done to get started in this setup.
Webpack.config.js is:
module.exports = {
entry: './app/app.jsx',
output: {
path: __dirname,
filename: './public/bundle.js'
},
resolve: {
modules: [__dirname, 'node_modules'],
alias: {
Greeter: 'app/components/Greeter.jsx',
GreeterMessage: 'app/components/GreeterMessage.jsx',
GreeterForm: 'app/components/GreeterForm.jsx',
},
extensions: ['.js', '.jsx']
},
// resolveLoader: {
// fallback: '/usr/local/lib/node_modules'
// },
module :{
rules:[{
// use : 'babel-loader',
loader: 'babel-loader',
query :{
presets:['react','es2015']
// ,'es2017'
},
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/
}
]
}
};
I had the same problem; I fixed it by installing the babel-loader module:
yarn add -D babel-loader
or
npm install --save babel-loader

Bundle sha3/binary modules with Webpack

Webpack warns when I bundle my source as it can't resolve the 'sha3' module.
$ npm run build
WARNING in ./~/keccakjs/index.js
Module not found: Error: Can't resolve 'sha3' in '<PROJ>\node_modules\keccakjs'
# ./~/keccakjs/index.js 2:19-34
# ./~/<lib>/index.js
# ./lib/<file>.js
Reason being the sha3 library has no js files.
Creating library <proj>\node_modules\sha3\build\Release\sha3.lib and object <proj>\node_modules\sha3\build\Release\sha3.exp
I am able to run require('sha3') in my project, however webpack cannot resolve it.
I looked at the docs here, regarding how webpack resolves libs.
Could someone point me to how I can include sha3 in/with my bundle.
My Webpack config:
module.exports = {
target: 'node',
entry: "./<lib>.js",
devtool: "source-map",
node: {
__dirname: false,
__filename: false,
},
output: {
path: "./dist",
filename: "<lib>.min.js"
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
})
]
}
What actually ended up working for me was:
resolve: {
alias: {
sha3: path.join(__dirname,'node_modules/sha3/build/Release/sha3.node')
},
},
module: {
rules: [
{test: /\.node$/, use: 'node-loader'},
]
},
That way I told it which file to import, when it wasn't able to resolve sha3. And the node-loader packages in the .node file!
Try using the binary loader from webpack from here. Then you can:
1) Define loaders in your WebPack config:
module.exports = {
target: 'node',
entry: "./<lib>.js",
devtool: "source-map",
node: {
__dirname: false,
__filename: false,
},
output: {
path: "./dist",
filename: "<lib>.min.js"
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
})
],
module: {
loaders: [
{ test: /sha3$/, loader: 'binary' }
]
}
}
2) Use the loader directly in your import:
require('binary!sha3');

Resources