Error when compiling with webpack and babel-loader - reactjs

I cannot seem to compile using the babel 6 loader and webpack. It's driving me mad. Has anyone else come across this problem? I cannot for the life of me see where I am screwing up. :)
Console Log
ERROR in ./~/redux/lib/index.js
Module build failed: ReferenceError: [BABEL] /Users/montague/Sites/redux/routing/node_modules/redux/lib/index.js: Unknown option: /Users/montague/Sites/redux/routing/node_modules/redux/.babelrc.stage
at Logger.error (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/logger.js:43:11)
at OptionManager.mergeOptions (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:245:18)
at OptionManager.addConfig (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:206:10)
at OptionManager.findConfigs (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:347:16)
at OptionManager.init (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:392:12)
at File.initOptions (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/index.js:191:75)
at new File (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/index.js:122:22)
at Pipeline.transform (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/pipeline.js:42:16)
at transpile (/Users/montague/Sites/redux/routing/node_modules/babel-loader/index.js:14:22)
at Object.module.exports (/Users/montague/Sites/redux/routing/node_modules/babel-loader/index.js:83:14)
# ./src/js/main.js 11:13-29
ERROR in ./~/react-redux/lib/index.js
Module build failed: ReferenceError: [BABEL] /Users/montague/Sites/redux/routing/node_modules/react-redux/lib/index.js: Unknown option: /Users/montague/Sites/redux/routing/node_modules/react-redux/.babelrc.stage
at Logger.error (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/logger.js:43:11)
at OptionManager.mergeOptions (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:245:18)
at OptionManager.addConfig (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:206:10)
at OptionManager.findConfigs (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:347:16)
at OptionManager.init (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:392:12)
at File.initOptions (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/index.js:191:75)
at new File (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/index.js:122:22)
at Pipeline.transform (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/pipeline.js:42:16)
at transpile (/Users/montague/Sites/redux/routing/node_modules/babel-loader/index.js:14:22)
at Object.module.exports (/Users/montague/Sites/redux/routing/node_modules/babel-loader/index.js:83:14)
# ./src/js/main.js 17:18-40
ERROR in ./~/redux-router/lib/index.js
Module build failed: ReferenceError: [BABEL] /Users/montague/Sites/redux/routing/node_modules/redux-router/lib/index.js: Unknown option: /Users/montague/Sites/redux/routing/node_modules/redux-router/.babelrc.stage
at Logger.error (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/logger.js:43:11)
at OptionManager.mergeOptions (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:245:18)
at OptionManager.addConfig (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:206:10)
at OptionManager.findConfigs (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:347:16)
at OptionManager.init (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/options/option-manager.js:392:12)
at File.initOptions (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/index.js:191:75)
at new File (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/file/index.js:122:22)
at Pipeline.transform (/Users/montague/Sites/redux/routing/node_modules/babel-core/lib/transformation/pipeline.js:42:16)
at transpile (/Users/montague/Sites/redux/routing/node_modules/babel-loader/index.js:14:22)
at Object.module.exports (/Users/montague/Sites/redux/routing/node_modules/babel-loader/index.js:83:14)
# ./src/js/main.js 13:19-42
webpack.config.js
var path = require('path');
module.exports = {
entry: path.resolve(__dirname + "/src/js/main.js"),
output: {
path: path.resolve(__dirname + "/dist/js/bundle.js")
},
module: {
loaders: [
{
test: /\.jsx?/,
excludes: /(node_modules|bower_components)/,
loader: "babel",
query: {
presets:['es2015']
}
}
]
}
}
main.js
import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';
import {createStore, compose, combineReducers} from 'redux';
import {
ReduxRouter,
routerStateReducer,
reduxReactRouter,
pushState
} from 'redux-router';
import {Route, Link} from 'react-router';
import {Provider, connect} from 'react-redux';
import {createHistory} from 'history';

According to the error it seems that redux is complaining about the stage option. It is probably because redux is still using Babel 5. This stage option has been removed from Babel 6.
Module build failed: ReferenceError: [BABEL]
/Users/montague/Sites/redux/routing/node_modules/redux/lib/index.js:
Unknown option:
/Users/montague/Sites/redux/routing/node_modules/redux/.babelrc.stage
But you shouldn't be running through babel those files. Hence something in your webpack.config.js should be wrong. Probably because your exclude field has an extra s.
Change:
excludes: /(node_modules|bower_components)/,
^
With:
exclude: /(node_modules|bower_components)/,

Try create a .babelrc file (root) without stage property. You can create just a empty brackets if you don't need set any property.
{}

Try installing the preset first, since babel 6 does not transform anything by default but requires a preset to define its transformation.
npm install --save-dev babel-preset-es2015
and for react:
npm install --save-dev babel-preset-react
Now add the preset to the .babelrc file:
{
"presets": ["es2015"]
}
This should do the trick, its exactly what I had to do to solve this.

Forget where I saw this (lemme know if it was you so I can give credit) but this command has helped fix a multitude of babel reference errors for me.
rm $( find node_modules -name .babelrc)

If you exclude node_modules from your loaders, then how are you going to deal with node modules which are coded using es6?

Related

Vitejs | Uncaught Error: Dynamic require of "<path>.svg" is not supported

I'm trying to use react-flagpack in my project that uses Vite, but whenever I use it i get the following error:
Uncaught Error: Dynamic require of "node_modules/flagpack-core/dist/flags/cDBuMQWP.svg" is not supported
Is this an issue with Vite? or am I doing something wrong.
Thanks in advance!
As of June 14th 2021 it's now supported. :3
Can you check if this works? I don't know if it will for react-flagpack; this is likely a require statement that is breaking the build... I found a solution using #originjs/vite-plugin-commonjs, which I posted here.
First install the package:
yarn add #originjs/vite-plugin-commonjs -D
or
npm i #originjs/vite-plugin-commonjs -D
And then, in your vite.config file:
import { defineConfig } from 'vite';
import { viteCommonjs, esbuildCommonjs } from '#originjs/vite-plugin-commonjs';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
viteCommonjs(),
],
optimizeDeps: {
esbuildOptions: {
plugins: [
// Solves:
// https://github.com/vitejs/vite/issues/5308
esbuildCommonjs(['react-flagpack'])
],
},
},
});
Then, try loading your file normally. This worked for me using tiny-react-slider which was using a require statement for a .css file

Module not found: Error: Can't resolve 'zlib'

I am trying to migrate a CRA react application to NX, following steps on the official site
When I hit nx serve
I am facing the following error:
ERROR in C:/dev/nx-dev/scandy/node_modules/#react-pdf/png-js/dist/png-js.browser.es.js
Module not found: Error: Can't resolve 'zlib' in 'C:\dev\nx-dev\scandy\node_modules#react-pdf\png-js\dist'
ERROR in C:/dev/nx-dev/scandy/node_modules/#react-pdf/pdfkit/dist/pdfkit.browser.es.js
Module not found: Error: Can't resolve 'zlib' in 'C:\dev\nx-dev\scandy\node_modules#react-pdf\pdfkit\dist'
Knowing that: before I start migration my project worked fine.
npm version: 6.14.11
node version: 14.16.0
I've tried to hit npm install zlib yet I get
Cannot find module './zlib_bindings'
For some reason, VSCode inserted import e from 'express' at the top of my file in react
import { response } from 'express';
I delete the above import line and then the problem is resolved, all the errors are gone after the above change.
It's about Webpack 5 and its default config you use for React app. I followed an advice from here: https://github.com/nrwl/nx/issues/4817#issuecomment-824316899 and React NX docs for how to use custom webpack config.
Create a custom webpack config, say, in /apps/myapp/webpack.config.js and reference it in workspace.json instead of "webpackConfig": "#nrwl/react/plugins/webpack". It should be "webpackConfig": "apps/myapp/webpack.config.js".
Content for webpack.config.js:
const nrwlConfig = require("#nrwl/react/plugins/webpack.js");
module.exports = (config, context) => {
// first call it so that #nrwl/react plugin adds its configs
nrwlConfig(config);
return {
...config,
node: undefined
};
};
So, this config change makes webpack correctly understand what polyfills are needed.
Alternatively, you can do the following:
const nrwlConfig = require("#nrwl/react/plugins/webpack.js");
module.exports = (config, context) => {
// first call it so that #nrwl/react plugin adds its configs
nrwlConfig(config);
return {
...config,
resolve: {
...config.resolve,
alias: {
...config.resolve.alias,
stream: require.resolve('stream-browserify'),
zlib: require.resolve('browserify-zlib'),
}
}
};
};
For me it was the code:
import { response } from 'express'
This was entered automatically by VSCode at the beginning of the file.
Deleting it solved the problem.
In my case was because I tried to type 'Text' and suddenly, the autocomplete added me this line on top:
import { text } from 'express';
Just deleted it and it worked fine.
Go Search Icon in VSCode search "express" you may get things like
import { text } from 'express'
import { Router } from 'express'
import { X,Y,Z } from 'express'
delete this line your app will work fine

Unable to resolve an image which is shared between web (react) and mobile (react-native) projects

I have a custom npm package created in directory web_with_weback (web react project). The package is built using webpack and contains one .png image. The package is loaded by using npm link inside another directory which is a react native project named mobile_with_metro. So in short, I want to have an npm package which among other things will share images from web to mobile. So to give you some context, here is how the two projects are setup.
The web project has the following structure.
Where the index.ts contains:
import TestImage from './testimage.png';
export {
TestImage
};
webpack.config.js
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
const CopyPlugin = require("copy-webpack-plugin");
module.exports = {
entry: {
images: {import: './src/images/index.ts', filename: 'images/index.js'}
},
externals: [nodeExternals()],
output: {
libraryTarget: 'commonjs'
},
plugins: [
new CleanWebpackPlugin(),
new CopyPlugin({
patterns: [
{ from: "src/images/index.d.ts", to: "images/index.d.ts" }
],
}),
],
module: {
rules: [
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.(png|jpe?g|gif|svg)$/i,
type: 'asset/inline'
}
]
}
}
I use webpack (v5.19.0). I use the latest feature from webapack asset/inline which is a replacement for the previous used url-loader.
dist folder after webpack build looks the following.
By using npm link in the dist folder and npm link #test/web_with_webpack in mobile_with_metro I make the built package available in the mobile app directory.
Now when I try to import the image and render it in an Image component in react native I get the following error:
error: Error: Unable to resolve module `#test/web_with_webpack/images` from `App.tsx`: #test/web_with_webpack/images could not be found within the project or in these directories:
node_modules/#test/web_with_webpack
If you are sure the module exists, try these steps:
1. Clear watchman watches: watchman watch-del-all
2. Delete node_modules: rm -rf node_modules and run yarn install
3. Reset Metro's cache: yarn start --reset-cache
4. Remove the cache: rm -rf /tmp/metro-*
at ModuleResolver.resolveDependency (/home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:186:15)
at ResolutionRequest.resolveDependency (/home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/node-haste/DependencyGraph/ResolutionRequest.js:52:18)
at DependencyGraph.resolveDependency (/home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/node-haste/DependencyGraph.js:287:16)
at Object.resolve (/home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/lib/transformHelpers.js:267:42)
at /home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/DeltaBundler/traverseDependencies.js:434:31
at Array.map (<anonymous>)
at resolveDependencies (/home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/DeltaBundler/traverseDependencies.js:431:18)
at /home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/DeltaBundler/traverseDependencies.js:275:33
at Generator.next (<anonymous>)
at asyncGeneratorStep (/home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/DeltaBundler/traverseDependencies.js:87:24)
Here is the react native App.tsx which imports the image.
import React from 'react';
import {
Image
} from 'react-native';
import {TestImage} from '#test/web_with_webpack/images';
const App = () => {
return (
<>
<Image source={{
uri: TestImage
}}/>
</>
);
};
To me it seems that the metro bundler can't understand what webpack has generated as an image 'path'.
Is there anything that I am missing here?
EDIT:
I tried using it in another react web project (which is setup with CRA) and it works. So, there is something that metro bundler in react native does not understand in the built package.

Jest and file-loader import

I'm currently importing a module using file loader in one of my files in a react app (CRA):
"file-loader?name=scripts/[name].[hash].js!jsstore/dist/jsstore.worker.min.js"
When running Jest, it throws this error:
Cannot find module 'file-loader?name=scripts/[name].[hash].js!jsstore/dist/jsstore.worker.min.js'
I've attempted different configs in package.json for Jest, by setting either modulePathIgnorePatterns and moduleNameMapper, but neither config setting works:
"modulePathIgnorePatterns": [
"file-loader?name=scripts/[name].[hash].js!jsstore/dist/jsstore.worker.min.js"
]
"moduleNameMapper": {
"file-loader?name=scripts/[name].[hash].js!jsstore/dist/jsstore.worker.min.js": "<rootDir>/node_modules/jsstore/dist/jsstore.worker.min.js"
}
You can map this import to a file that will return a string which what file-loader returns;
moduleNameMapper: {
"^file\-loader":"<rootDir>/__mocks__/fileMock.js",
}
// __mocks__/fileMock.js
module.exports = 'file-path-mock';

babel-loader, webpack, ES2015 modules: "Element type is invalid"

Github repo with everything in: https://github.com/b-paul/react-lifecycle
Update 12/18: A large part of the problem was the npm commands used to run the project. I had noticed that npm build was not successful, but npm start reported building OK. Full answer below on why that didn't work as expected. The rest of this question is being kept for posterity.
I'm having trouble with basic setup for my first webpack project. I'm using React and Babel, and the following webpack.config.js:
var path = require('path');
module.exports = {
entry: [ path.resolve('./js/app.js'),
'webpack-dev-server/client?http://localhost:8080' ],
output: {
path: path.resolve('./js/build'),
filename: 'app.min.js'
},
module: {
loaders: [
{ test: /\.jsx?$/,
loader: 'babel',
query: {
presets: ['react', 'stage-1', 'es2015']
},
include: path.resolve('js/') } ]
},
devtool: 'source-map'
};
js/app.js
import Lifecycle from './components/lifecycle';
import React from 'react';
import {render} from 'react-dom';
var shell = document.createElement('div');
shell.className = 'app-shell';
document.body.appendChild(shell);
render(<Lifecycle />, shell);
js/components/lifecycle.js
import React from 'react';
class Lifecycle extends React.Component {
render() {
return (
<div>Hello, world</div>
);
}
}
export default Lifecycle;
The above builds without errors, but it won't render "Hello, world". I'm getting the error, "Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined." in the browser console.
I can trace this as far as some generated babel code that tries to check if my module Lifecycle is an ES6 module (babel recognizes it as such) and expects it to have a property default on the internal module object (it doesn't). Here is that generated code:
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _lifecycle = __webpack_require__(1);
var _lifecycle2 = _interopRequireDefault(_lifecycle);
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(159);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(0, _reactDom.render)(_react2.default.createElement(_lifecycle2.default, null), document.body);
/***/ }
Final note: I referenced https://github.com/code0wl/react-example-es2015 several times for setup, and I can clone and build that example repo into a working app with no problems. I'm realize that I must've missed some essential part of what's happening in that repo, but I can't see it.
works for me
git clone https://github.com/b-paul/react-lifecycle.git
cd react-lifecycle.git
npm install
npm run build
npm run start
# go to http://localhost:8090/index.html
Is there are reason for creating your app's container div dynamically in app.js rather than just putting it in index.html? I cloned your repo and got the app to build by making the following changes:
index.html:
<body>
<div id="app-shell"></div>
<script type="application/javascript" src="js/build/app.min.js"></script>
</body>
app.js
import React from 'react';
import {render} from 'react-dom';
import Lifecycle from './components/lifecycle';
render(<Lifecycle />, document.getElementById('app-shell'));
I think the “Element type is invalid” error was a red herring. Prior to that I was seeing:
Warning: React.createElement: type should not be null, undefined,
boolean, or number. It should be a string (for DOM elements) or a
ReactClass (for composite components).warning #
app.min.js:2233createElement # app.min.js:19531(anonymous function) #
app.min.js:61__webpack_require__ # app.min.js:20(anonymous function) #
app.min.js:40(anonymous function) # app.min.js:43 app.min.js:2233
Warning: render(): Rendering components directly into document.body is
discouraged, since its children are often manipulated by third-party
scripts and browser extensions. This may lead to subtle reconciliation
issues. Try rendering into a container element created for your app.
Which is likely due to the way you are creating the shell element in app.js...
This question should have been called "why won't my NPM scripts update my bundle."
At some point early in development, I had successfully bundled my code with webpack. That bundle was on disk as js/build/app.min.js. After that point, I thought I was using NPM scripts from package.json to rebuild the app with each change, but in-browser, I was still getting the old behavior (from the original bundle). I missed two facts:
Fact 1: npm build is a recognized NPM command, but it does not invoke scripts.build from package.json. As in #zhongjie-wu 's answer, I needed to do npm run build. npm start, on the other hand, does invoke scripts.start, which successfully built a bundle with webpack-dev-server.
Fact 2: webpack-dev-server does not recognize output.path from the webpack config file as part of the route when serving the rebuilt bundle. Because of this, given the configuration I used, webpack builds to /js/build/app.min.js, but webpack-dev-server serves that bundle from memory as /app.min.js. Since my HTML references the original, I didn't see the dev server bundle.
Layout.js
export default class Layout extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="Layout">
</div>
)
}
};
.babelrc
need add stage-1 preset for try transpiling classes
{
"presets": ["stage-1", "es2015", "react"],
"plugins": ["transform-runtime"]
}
and entry file need doing ES5 export:
import React from 'react';
import Layout from './Layout';
import {render} from 'react-dom';
if (typeof document !== 'undefined') {
render(<Layout />, document.getElementById('app'));
}
module.exports = Layout;
its working for me

Resources