Unable to build ES6 version of my React App with webpack and babel-preset-env [duplicate] - reactjs

This question already has answers here:
Webpack + Babel error
(2 answers)
Closed 5 years ago.
I decided to rewrite my existing React App from ES5 to ES6. Below is my index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import ToDoList from './to-do-list.jsx';
//Put the components into HTML
ReactDOM.render(<ToDoList/>, document.getElementById('todo-wrapper'));
However when I try to build with webpack and launch the app I get the error that:
ERROR in ./src/app/index.js
Module parse failed: /home/sam/devzone/github/simple-react-todo-app/src/app/index.js Unexpected token (6:16)
You may need an appropriate loader to handle this file type.
|
| //Put the components into HTML
| ReactDOM.render(<ToDoList/>, document.getElementById('todo-wrapper'));
I have selected babel-preset-env instead of babel-preset-es2015, but I highly doubt that this is the cause. Below are snapshots of my package.json and my webpack.config.js respectively.
package.json
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "npm run build",
"build": "webpack -d && webpack-dev-server --content-base src/ --inline --hot --port 1234"
},
...
"dependencies": {
"react": "^16.0.0",
"react-dom": "^16.0.0"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.7",
"eslint": "^4.7.2",
"eslint-plugin-react": "^7.4.0",
"style-loader": "^0.18.2",
"webpack": "^3.6.0",
"webpack-dev-server": "^2.9.1"
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: path.resolve(__dirname, 'src') + '/app/index.js',
output: {
path: path.resolve(__dirname, 'dist') + '/app',
filename: 'bundle.js',
publicPath: '/app/'
},
module: {
loaders: [
{
test: /\.jsx?$/,
include: path.resolve(__dirname, 'src'),
loader: 'babel-loader',
query: {
"presets": [
["env", {
"loose": true,
"modules": false,
"useBuiltIns": true,
"debug": true,
"include": ["transform-es2015-classes"]
}],
"react"
],
"plugins": [
"babel-plugin-transform-es2015-parameters",
"babel-plugin-transform-es2015-destructuring"
]
}
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}
],
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
}
};
As it might be evident that I did a bit trial and error myself, but I seem to be totally lost now.
The app folder structure and other relevant files can be seen inside my repo here.
Any pointers would be appreciated.

Your webpack's config is wrong (it's old config from Webpack 1)
You should change it to:
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: path.resolve(__dirname, 'src') + '/app/index.js',
output: {
path: path.resolve(__dirname, 'dist') + '/app',
filename: 'bundle.js',
publicPath: '/app/'
},
module: {
rules: [
{
test: /\.jsx?$/,
include: path.resolve(__dirname, 'src'),
loader: 'babel-loader',
options: {
"presets": [
["env", {
"loose": true,
"modules": false,
"useBuiltIns": true,
"debug": true,
"include": ["transform-es2015-classes"]
}],
"react"
],
"plugins": [
"babel-plugin-transform-es2015-parameters",
"babel-plugin-transform-es2015-destructuring"
]
}
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
}
};

Just change
test: /\.jsx?$/,
To
test: /.(js|jsx)?$/,

Related

Webpack 5.68 not tree shaking ESM imports

I can't get tree shaking to work correctly on my project running Webpack 5.68 and Babel 7.17.0.
If I import my component like this everything works fine and dandy.
import { InlineNotification } from 'carbon-components-react/es/components/Notification';
If I import like this, the entire library is imported into my bundle.
import { InlineNotification } from 'carbon-components-react';
It is not an issue with carbon-components-react, I was just giving an example. This happens with all libraries.
Below is my code. I'm not sure what I am missing!
// .babelrc
{
"presets": [
[
"#babel/preset-env",
{
"modules": false
}
],
"#babel/preset-react"
],
"plugins": [
"react-hot-loader/babel",
"#babel/plugin-transform-modules-commonjs",
"#babel/plugin-proposal-class-properties"
]
}
// package.json
{
"name": "my app",
"engines": {
"node": "^8.9.0",
"npm": ">= 5.5.0"
},
"main": "index.jsx",
"scripts": {
"dev": "npx foreman --procfile Procfile-dev start",
"build": "npm run build:prod",
"build:dev": "webpack --progress --config webpack.build.dev.js",
"build:prod": "NODE_ENV=production webpack --progress --config webpack.build.prod.js",
},
"devDependencies": {
"#babel/core": "^7.17.0",
"#babel/plugin-proposal-class-properties": "^7.16.7",
"#babel/plugin-transform-modules-commonjs": "^7.16.8",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.16.7",
"babel-jest": "^26.6.3",
"babel-loader": "^8.2.3",
"webpack": "^5.68.0",
"webpack-bundle-analyzer": "^4.5.0",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.11.3"
},
"dependencies": {
"#carbon/icons-react": "^10.45.0",
"#carbon/themes": "^10.50.0",
"carbon-components": "^10.52.0",
"carbon-components-react": "^7.52.0",
"css-loader": "^1.0.1",
"foreman": "^3.0.1",
"react": "^16.14.0",
"react-dom": "^16.14.0",
"react-hot-loader": "^4.13.0",
"webpack-merge": "^4.2.2"
}
}
// webpack.common.js
const webpack = require('webpack');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebPackPlugin({
template: './template/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: './index.jsx',
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.scss?/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader', options: {limit: 100000}
}
]
},
plugins: [
HtmlWebpackPluginConfig,
],
resolve: {
fallback: {
fs: false,
net: false,
tls: false
}
}
};
// webpack.build.prod.js
const webpack = require('webpack');
const path = require('path');
const merge = require('webpack-merge');
const common = require('./webpack.common');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = merge(common, {
name: 'build:prod',
mode: 'production',
output: {
filename: 'dist/js/bundles/bundle.[contenthash].js',
path: path.resolve(__dirname, '.')
},
optimization: {
runtimeChunk: {
name: 'manifest',
},
splitChunks: {
chunks: 'all'
}
},
plugins: [
new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment$/,
}), // ignore all of the momentjs timezones
new BundleAnalyzerPlugin({ defaultSizes: 'gzip', generateStatsFile: true }),
]
});
I fixed this, the issue was a plugin in my .babelrc file
#babel/plugin-transform-modules-commonjs. I needed to remove this and ensure all of my imports/exports were using ESM rather than commonJS module.exports.

Babel requiring module that isn't used?

I'm new to React, webpack, Babel.... all of it. Trying to setup a vanilla project where I want to utilize Salesforce Lightning Design System for React. npm run start shows the following error:
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: [BABEL] /Users/brandor/test/react_tut/src/index.js: Cannot find module 'babel-preset-env'
Require stack:
- /Users/brandor/test/react_tut/node_modules/#salesforce/babel-preset-design-system-react/index.js
I'm not sure why it's stating that 'babel-preset-env' is required. Shouldn't that have been installed when I installed the slds modules with the following?
$ npm install #salesforce-ux/design-system #salesforce/design-system-react
If I do install the module (along with one other it complains about) then I get something that seems to be related to this issue, but I'm using what looks like the correct presets in my babel.config.js file.
The other error is:
TypeError: /Users/brandor/test/react_tut/src/components/App.js: Cannot read property 'bindings' of null which
Not sure if this is an issue with webpack config, babel, or incorrect version of something.
package.json
{
"name": "react_tut",
"version": "1.0.0",
"description": "Boilerplate stuff",
"main": "index.js",
"scripts": {
"build": "webpack --mode production",
"start": "webpack-dev-server --mode development --open --hot"
},
"license": "MIT",
"dependencies": {
"#salesforce-ux/design-system": "^2.11.6",
"#salesforce/design-system-react": "^0.10.18",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-export-extensions": "^6.22.0",
"core-js": "^3.6.4",
"react": "^16.12.0",
"react-dom": "^16.12.0"
},
"devDependencies": {
"#babel/cli": "^7.8.4",
"#babel/core": "^7.8.4",
"#babel/preset-env": "^7.8.4",
"#babel/preset-flow": "^7.8.3",
"#babel/preset-react": "^7.8.3",
"babel-loader": "^8.0.6",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"css-loader": "^3.4.2",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.9.0",
"url-loader": "^4.0.0",
"webpack": "^4.41.6",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
}
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './src/index.js',
resolve: {
modules: ['src', 'node_modules'],
extensions: ['.js', '.jsx']
},
output: {
path: path.join(__dirname, '/dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.jsx?$/,
include: [
path.join(__dirname, 'src/js'),
path.join(__dirname, 'node_modules/#salesforce/design-system-react'),
],
exclude: [
path.join(
__dirname,
'node_modules/#salesforce/design-system-react/node_modules',
),
],
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
},
},
],
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
},
{
test: /\.(svg|gif|jpe?g|png)$/,
loader: 'url-loader?limit=10000'
},
{
test: /\.(eot|woff|woff2|ttf)$/,
loader: 'url-loader?limit=30&name=assets/fonts/webfonts/[name].[ext]'
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'src', 'index.html'),
}),
],
};
babel.config.js
'use strict';
const presets = ['#babel/preset-react', '#babel/preset-flow', '#salesforce/babel-preset-design-system-react'];
module.exports = {
presets: [
...presets,
[
'#babel/preset-env',
{
modules: false,
corejs: '3',
useBuiltIns: 'usage',
},
],
],
env: {
test: {
presets: [
...presets,
[
'#babel/preset-env',
{
targets: { node: 'current' },
corejs: '3',
useBuiltIns: 'usage',
},
],
],
},
},
};

webpack bundle file is not being generated with no errors

I am new to react, trying to learn webpack configuration. I am using webpack4 for my project, however, after setting up webpack, the bundle files are not generated, neither the js file nor the html file and there is no error.
The output on the console says "compiled successfully". How do i fix this. I have been struggling for about a week and no online resource seems to give me what i want.
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const port = process.env.PORT || 3000;
const paths = {
DIST: path.resolve(__dirname, 'dist'),
SRC: path.resolve(__dirname, 'src'),
JS: path.resolve(__dirname, 'src/js')
}
const htmlPlugin = new HtmlWebpackPlugin({
template: "./src/index.html",
filename: "./index.html"
});
module.exports = {
mode: 'development',
entry: path.join(paths.JS, 'index.js'),
output: {
path: paths.DIST,
filename: 'app.bundle.js'
},
module:{
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader",
options:{
modules: true,
importLoaders: 1,
localIndentName: "[name]_[local]_[hash:base64]",
sourceMap: true,
minimize: true,
camelCase:true
}
}
]
}
]
},
plugins: [htmlPlugin],
devServer: {
publicPath: paths.DIST,
host: 'localhost',
port: port,
historyApiFallback: true,
open:true,
hot: true
}
};
Make sure all path correctly, not have missing file.
src/js/index.js
src/index.html
make sure run webpack correctly to show log like:
package.json
"scripts": {
"start": "webpack --config webpack.config.js --bail --progress --profile"
},
and run by npm start, then will show the log.
if you want, you can use new babel version. change your bable with this:
"dependencies": {
"#babel/core": "^7.0.0-beta.42",
"#babel/preset-env": "^7.0.0-beta.42",
"babel-eslint": "^8.0.3",
"babel-loader": "^8.0.0-beta.0",
"css-loader": "^0.28.11",
"html-webpack-plugin": "^3.1.0",
...
"style-loader": "^0.20.3",
"webpack": "^4.4.1",
"webpack-cli": "^2.0.13"
},
.babelrc
{
"presets": ["#babel/preset-env"],
"plugins": ["#babel/plugin-proposal-object-rest-spread"]
}
then update your webpack rule:
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: [require('#babel/plugin-proposal-object-rest-spread')]
}
},
exclude: /node_modules/
},

Cant Import CSS files into React Project

when i tried to import css file it showed error that loaders are missing. so i have installed css-loader and style-loader packages. if i add those packages to webpack.config.js i get following error. i dont know how to resolve it.
ERROR in ./node_modules/css-loader!./src/index.js
Module build failed: Unknown word (1:1)
> 1 | import React from 'react';
| ^
2 | import ReactDOM from 'react-dom';
3 | import {App} from './components/App';
4 |
# ./src/index.js 3:14-73
# multi (webpack)-dev-server/client?http://localhost:8080
./src/index.js
Webpack.config.js
module.exports = {
entry: [
'./src/index.js'
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader","style-loader","css-loader"],
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './dist'
}
};
i have installed following dependecies
package.json
{
"name": "Reactjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --config ./webpack.config.js --mode
development"
},
"keywords": [],
"author": "",
"license": "ISC",
"babel": {
"presets": [
"env",
"react",
"stage-2"
]
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "^0.28.11",
"style-loader": "^0.20.3",
"webpack": "^4.2.0",
"webpack-cli": "^2.0.12",
"webpack-dev-server": "^3.1.1"
},
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-router-dom": "^4.2.2"
}
}
Modifie your webpack.config.js to this and import your css file on your App component like this import './file.css'; (assuming that the css file is in the same directory as your App component)
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './dist'
}
};
You need to add a separate rule for css to your webpack.config in order to load css into your project.
...
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"]
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
...
You're using style-loader and css-loader to transform your .jsx files which is going to throw an error.

You may need an appropriate loader to handle this file type.eith react.js,webpack,babel

I am trying to compile js file with react using webpack with babel, but I am getting the following error message:
ERROR in ./js/IntroAndWorkSpace.js
Module parse failed: C:\FULLTIME\STUDY METERIAL\ReactJS\NewReactPoject\js\IntroAndWorkSpace.js Unexpected token (1:8)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (1:8)
here is my js file
import* React from 'react'
import* ReactDOM from 'react-dom',
ReactDOM.render(<h1>headingthe of page</h1>,
document.getElementById('head')
);
here is pakeje.json
{
"name": "newreactproject",
"version": "1.0.0",
"description": "myreactproject for learning react",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "priya",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.14.0",
"babel-loader": "^6.2.5",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-react-html-attrs": "^2.0.0",
"babel-plugin-transform-class-properties": "^6.11.5",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.14.0",
"babel-preset-react": "^6.11.1",
"babel-preset-stage-0": "^6.5.0",
"react": "^15.3.1",
"react-dom": "^15.3.1",
"webpack": "^1.13.2"
}
}
here is config.js
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
module.exports = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./js/scripts.js",
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'],
}
}
],
output: {
path: __dirname + "/js",
filename: "scripts.min.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
It looks like you have everything set up correctly. I believe the problem is that your webpack configuration file is configured to load files with the extension .jsx with the babel loader using the react and ES2015 presets, but the file you're attempting to load (IntroAndWorkSpace.js) doesn't end with the .jsx extension.
Since it's probably a good idea to be consistent with your file extensions, you have two options for fixing this:
1) Change the extension of the file you're trying to load to .js instead of .jsx.
2) Change the loader test to load files with the extension .js instead of .jsx:
loaders: [
{
test: /\.js?$/,
...
}
]
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'],
}
}
],

Resources