Can't resolve 'babel-loader' - node.js

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

Related

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.

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

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
}}

Configuration.resolve has an unknown property 'root'

I get the following error :
Invalid configuration object. Webpack has been initialised using a
configuration object that does not match the API schema.
- configuration.resolve has an unknown property 'root'. These properties are valid: object { alias?, aliasFields?,
cachePredicate?, descriptionFiles?, enforceExtension?,
enforceModuleExtension?, extensions?, fileSystem?, mainFields?,
mainFiles?, moduleExtensions?, modules?, plugins?, resolver?,
symlinks?, unsafeCache?, useSyncFileSystemCalls? }
I use webpack 2.3.2.
My webpack.config.js looks like this :
module.exports= {
entry:'./public/app.jsx',
output: {
path: __dirname,
filename:'./public/bundle.js'
},
resolve: {
root: __dirname,
alias:{
Mod1: 'public/components/mod1.jsx',
Mod2:'public/components/mod2.jsx',
Mod3: 'public/components/mod3.jsx'
},
extensions: ['*','.js','.jsx']
},
module :{
loaders:[{
loader :'babel-loader',
query :{
presets:['react','es2015','es2017']
},
test:/\.jsx?$/,
exclude:/(node_modules|bower_components)/
}]
}
};
resolve.root is Webpack 1 configuration and doesn't exist for Webpack 2.
For Webpack 2 you can use resolve.modules: https://webpack.js.org/configuration/resolve/#resolve-modules
module.exports= {
entry:'./public/app.jsx',
output: {
path: __dirname,
filename:'./public/bundle.js'
},
resolve: {
modules: [__dirname, 'node_modules'],
alias:{
Mod1: 'public/components/mod1.jsx',
Mod2:'public/components/mod2.jsx',
Mod3: 'public/components/mod3.jsx'
},
extensions: ['*','.js','.jsx']
},
module :{
rules:[{
use : 'babel-loader',
query :{
presets:['react','es2015','es2017']
},
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/
}]
}
};
I've also updated module.loaders -> module.rules as this is deprecated in Webpack 2.
Have you tried removing LINE 8? Does it through any errors?
As you've probably guessed it is throwing an error as you are trying to set a property which isn't valid.
There is a chance that the instructions you may have followed when configuring webpack is outdated.
Give it a go without LINE 8 and let me know if the problems persist and we can fix it together.

Webpack with babel-loader property types

I'm trying to migrate my node typescript apps (with exprees js server) to ES2015 with using Webpack.
First of all, I would like to use property types. I founded, than I need to user babel-loader and eslint. So, I installed this packages and implement it to my express app.:
This is my webpack.config.js
const webpack = require('webpack');
const WebpackErrorNotificationPlugin = require("webpack-error-notification");
module.exports =
{
entry: './src/test/test.js',
target: 'node',
debug: true,
output: {
path: './bin',
filename: 'test.bundle.js',
},
module: {
preLoaders: [{
test: /\.js?$/,
loaders: ['eslint'],
exclude: /node_modules/
}],
loaders: [{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel',
}]
},
eslint: {
failOnWarning: false,
failOnError: true
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
output: {
comments: false,
},
}),
new WebpackErrorNotificationPlugin()
]
}
.eslintrc
{
"parser": "babel-eslint",
"parserOptions": {
"sourceType": "module",
"allowImportExportEverywhere": false
}
}
And one of error codes:
export class CmsUserModel {
/**
* (description)
*
* #type {String}
*/
template: string;
/**
* (description)
*
* #type {string}
*/
pages: string[];
constructor() {
this.template = "";
this.pages = new Array<string>();
}
public static ToModel(model: ICmsUserModel) {
return <CmsUserModel>{
template : model.template,
pages : model.pages
};
}
}
There are two problems. The first is, then babal-eslint error handling is not too specified. For example this:
ERROR in ./src/models/cmsUserModel.js
/Users/petrtomasek/Projects/cms/src/models/cmsUserModel.js
44:40 error Parsing error: Unexpected token
✖ 1 problem (1 error, 0 warnings)
ERROR in ./src/models/cmsUserModel.js
Module build failed: Error: Module failed because of a eslint error.
/Users/petrtomasek/Projects/cms/src/models/cmsUserModel.js
44:40 error Parsing error: Unexpected token
✖ 1 problem (1 error, 0 warnings)
It's fine, but I would like to see standard error handling like in default webpack and babel loader with print current error line if is possible..?
And the second error is, then I still cannot use property Types as for example: template: string
What's wrong please?
Thank's for your time!
I think you should try the following steps,
1. npm install --save-dev babel-preset-es2015
2. Add query: { presets: ['es2015'] } to your webpack config with the babel loader.
loaders: [{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel',
query: { presets: ['es2015'] }
}]

Having trouble getting rollbar.js to build in a node/webpack-based project

We're hoping to use Rollbar.js in our node/webpack/babel/ES6/React-based project. It's not 100% clear what the right NPM package is to use, but it appears to be this one:
https://www.npmjs.com/package/rollbar
From there, the instructions are pretty straightforward: add a reference to package.json, install, and off you go. So here's the reference in package.json:
"rollbar": "0.6.2",
Running npm install appears to work just fine, but then when I run npm start, I get this error in the console:
ERROR in ./~/rollbar/lib/parser.js
Module not found: Error: Cannot resolve module 'fs' in [myProjectRoot]node_modules/rollbar/lib
# ./~/rollbar/lib/parser.js 7:9-22
ERROR in ./~/rollbar/package.json
Module parse failed: [myProjectRoot]node_modules/rollbar/package.json Unexpected token (2:9)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (2:9)
at Parser.pp.raise ([myProjectRoot]node_modules/webpack/node_modules/acorn/dist/acorn.js:923:13)
at Parser.pp.unexpected ([myProjectRoot]node_modules/webpack/node_modules/acorn/dist/acorn.js:1490:8)
at Parser.pp.semicolon ([myProjectRoot]node_modules/webpack/node_modules/acorn/dist/acorn.js:1469:73)
at Parser.pp.parseExpressionStatement ([myProjectRoot]node_modules/webpack/node_modules/acorn/dist/acorn.js:1994:8)
at Parser.pp.parseStatement ([myProjectRoot]node_modules/webpack/node_modules/acorn/dist/acorn.js:1772:188)
at Parser.pp.parseBlock ([myProjectRoot]node_modules/webpack/node_modules/acorn/dist/acorn.js:2009:21)
at Parser.pp.parseStatement ([myProjectRoot]node_modules/webpack/node_modules/acorn/dist/acorn.js:1753:19)
at Parser.pp.parseTopLevel ([myProjectRoot]node_modules/webpack/node_modules/acorn/dist/acorn.js:1666:21)
at Parser.parse ([myProjectRoot]node_modules/webpack/node_modules/acorn/dist/acorn.js:1632:17)
at Object.parse ([myProjectRoot]node_modules/webpack/node_modules/acorn/dist/acorn.js:885:44)
# ./~/rollbar/lib/notifier.js 14:18-44
I can't make any sense out of this. It appears to suggest that my webpack project cannot parse Rollbar's package.json file, but that doesn't seem possible, given that my webpack project has countless other NPM packages, each with their own package.json file.
Anybody run into this issue?
UPDATE:
In case it's relevant, here's our complete webpack.config.js file:
const path = require('path');
const webpack = require('webpack');
const glob = require('glob');
const modulesDirectories = glob.sync('src/**');
const assetsDirectories = glob.sync('assets/**');
Array.prototype.push.apply(
modulesDirectories,
assetsDirectories
);
modulesDirectories.push('assets');
modulesDirectories.push('/');
modulesDirectories.push('node_modules');
const modulesDirectoriesWithoutFiles = modulesDirectories.filter(directory => {
if (directory.slice(-4, -3) === '.' || directory.slice(-3, -2) === '.') {
return false;
}
return true;
});
module.exports = {
cache: true,
devtool: 'cheap-module-eval-source-map',
entry: [
'eventsource-polyfill',
'webpack-hot-middleware/client',
'./src/index.js'
],
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loader: 'babel',
query: {
// https://github.com/babel/babel-loader#options
cacheDirectory: true
},
include: path.join(__dirname, 'src'),
exclude: /node_modules/
},
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.woff|.ttf|.eot|.woff2$/, loader: `file-loader` },
{ test: /\.(png|jpe?g|gif|svg)$/, loader: `url-loader?limit=8192` },
]
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
FIREBASE_CONFIG: JSON.stringify({
apiKey: [ourApiKey],
authDomain: [ourDomain],
databaseURL: [ourUrl],
storageBucket: [ourBucket],
})
})
],
resolve: {
extensions: ['', '.js', '.jsx'],
root: __dirname,
modulesDirectories: modulesDirectoriesWithoutFiles,
}
};
SECOND UPDATE:
Still can't get things to build, but I've got a little more information. If I remove the Rollbar import from my code, then the console errors go away. I've tried importing Rollbar in two ways, as follows:
import rollbar from "rollbar";
var Rollbar = require('rollbar');
Both attempts produce the same error. If I add node: {fs: "empty"} to my webpack.config.js file, then the 'fs' error disappears, but the "appropriate loader" error remains.
I was encountering the same issue. I fixed it by:
Installing fs using npm install --save fs. Alternatively, you can add node: {fs: "empty"} to your webpack config, as suggested in comments. Either of these takes care of the fs import in rollbar/lib/parser.js.
Installing a json loader, then adding this loader to your webpack config under modules -> loaders. This informs webpack that it should use the json loader when loading JSON files. Webpack should then be able to import package.json in rollbar/lib/notifier.js.
module: {
loaders: [
{
test: /\.json$/,
loader: "json"
},
...
],
...
}

Resources