Can't get the JSX preprocessor to run from webpack [duplicate] - reactjs

This question already has answers here:
Babel file is copied without being transformed
(10 answers)
Closed 6 years ago.
I'm a beginner in React + Webpack.
I found a weird error in my hello world web app.
I'm using babel-loader in webpack to help me convert jsx into js, but it seems like babel can't understand jsx syntax.
Here are my dependencies:
"devDependencies": {
"babel-core": "^6.0.14",
"babel-loader": "^6.0.0",
"webpack": "^1.12.2",
"webpack-dev-server": "^1.12.1"
},
"dependencies": {
"react": "^0.14.1"
}
Here is my webpack.config.js
var path = require('path');
module.exports = {
entry: ['webpack/hot/dev-server',path.resolve(__dirname, 'app/main.js')],
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"}
]
}
};
Here is my app/main.js
var React = require("react");
React.render(<h1>hello world</h1>,document.getElementById("app"));
And this is the error message
ERROR in ./app/main.js
Module build failed: SyntaxError: ~/**/app/main.js: Unexpected token (2:13)
1 | var React = require("react");
> 2 | React.render(<h1>hello world</h1>,document.getElementById("app"));
| ^
at Parser.pp.raise (~/**/node_modules/babylon/lib/parser/location.js:24:13)
Thanks for you guys.

Add "babel-preset-react"
npm install babel-preset-react
and add "presets" option to babel-loader in your webpack.config.js
(or you can add it to your .babelrc or package.js: http://babeljs.io/docs/usage/babelrc/)
Here is an example webpack.config.js:
{
test: /\.jsx?$/, // Match both .js and .jsx files
exclude: /node_modules/,
loader: "babel",
query:
{
presets:['react']
}
}
Recently Babel 6 was released and there was a major change:
https://babeljs.io/blog/2015/10/29/6.0.0
If you are using react 0.14, you should use ReactDOM.render() (from require('react-dom')) instead of React.render(): https://facebook.github.io/react/blog/#changelog
UPDATE 2018
Rule.query has already been deprecated in favour of Rule.options. Usage in webpack 4 is as follows:
npm install babel-loader babel-preset-react
Then in your webpack configuration (as an entry in the module.rules array in the module.exports object)
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['react']
}
}
],
}

I ran into a similar issue when migrating from babel 5 to babel 6.
I was just running babel to compile the src to lib folder babel src --out-dir lib
I will share my setup for babel 6:
Ensure you have the following babel 6 devDependencies installed
"babel-core": "^6.7.6",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0"
Add your .babelrc file to the project:
{
"presets": ["es2015", "stage-0", "react"]
}

Since the answer above still leaves some people in the dark, here's what a complete webpack.config.js might look like:
var path = require('path');
var config = {
entry: path.resolve(__dirname, 'app/main.js'),
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel',
query:
{
presets:['es2015', 'react']
}
}]
},
};
module.exports = config;

For me the solution was to create the file .babelrc with this content:
{
"presets": ["react", "es2015", "stage-1"]
}

The following way has helped me (includes react-hot, babel loaders and es2015, react presets):
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel?presets[]=es2015&presets[]=react']
}
]

For those who still might be facing issue adding jsx to test fixed it for me
test: /\.jsx?$/,

This works perfect for me
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015','react']
}
},

You can find a really good boilerplate made by Henrik Joreteg (ampersandjs) here: https://github.com/HenrikJoreteg/hjs-webpack
Then in your webpack.config.js
var getConfig = require('hjs-webpack')
module.exports = getConfig({
in: 'src/index.js',
out: 'public',
clearBeforeBuild: true,
https: process.argv.indexOf('--https') !== -1
})

Related

Module build failed babel-loader Unexpected token "<"

There are a seemingly endless number of questions here and on github asking this question and none of the solutions work for me. I'm simply trying to update an old project and I'm consistently getting this error:
Module build failed (from ../node_modules/babel-loader/lib/index.js):
SyntaxError: /Users/user/Documents/project/src/index.js: Unexpected token (5:16)
The unexpected token is "<" ReactDOM.render("<"App />, ...);
package.json:
"devDependencies": {
"#babel/core": "^7.10.3",
"#babel/preset-env": "^7.10.3",
"#babel/preset-react": "^7.10.1",
"babel-loader": "^8.1.0",
...
}
webpack config: (webpack 4.43.0)
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
...
],
}
.babelrc:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
For context, the old babel packages work just fine.
Are there any other solutions to this issue?
Looks pretty standard. Had an issue after upgrading from v6 t v7 of babel , had to switch from .babelrc to config file which cleared the cached files. For quick trial you can add this in webpack and try
loader: 'babel-loader',
options: {
presets:["#babel/preset-env","#babel/preset-react" ]
},

ReferenceError: [BABEL] Unknown option: base.__esModule

i am trying react lazy component loading ,that will load component separately and then I got
unexpected token import
i changed my babel file and now error is
ReferenceError: [BABEL] E:\projectSir\latestProject1\tools\startMsg.js: Unknown option: base.__esModule. Check out http://babeljs.io/docs/usage/options/ for more info
at Logger.error (E:\projectSir\latestProject1\node_modules\babel-core\lib\transformation\file\logger.js:43:11)
at OptionManager.mergeOptions (E:\projectSir\latestProject1\node_modules\babel-core\lib\transformation\file\options\option-manager.js:307:20)
at OptionManager.init (E:\projectSir\latestProject1\node_modules\babel-core\lib\transformation\file\options\option-manager.js:506:10)
at File.initOptions (E:\projectSir\latestProject1\node_modules\babel-core\lib\transformation\file\index.js:243:89)
at new File (E:\projectSir\latestProject1\node_modules\babel-core\lib\transformation\file\index.js:159:72)
at Pipeline.transform (E:\projectSir\latestProject1\node_modules\babel-core\lib\transformation\pipeline.js:49:16)
at Object.transformFileSync (E:\projectSir\latestProject1\node_modules\babel-core\lib\api\node.js:152:10)
at compile (E:\projectSir\latestProject1\node_modules\babel-register\lib\node.js:129:20)
at loader (E:\projectSir\latestProject1\node_modules\babel-register\lib\node.js:158:14)
at Object.require.extensions.(anonymous function) [as .js] (E:\projectSir\latestProject1\node_modules\babel-register\lib\node.js:168:7)
my babel file is
{
"plugins": ["syntax-dynamic-import"],
"presets": ["env","react","es2015"],
"env": {
"development": {
"presets": [
"react-hmre"
]
}
}
}
my react code for this is
async loadLazyComponent () {
if(this.state.animation == null){
try{
const LazyComponent = await import('./animation.js')
this.setState({animation:React.createElement(LazyComponent.default)})
}catch(e){
this.setState({animation:<div>`failed ${e}`</div>})
}
}
}
and package.json file is
"babel-polyfill": "6.8.0",
"babel-preset-env": "^1.6.1",
and devDependencies are
"babel-cli": "^6.8.0",
"babel-core": "6.8.0",
"babel-loader": "6.2.4",
"babel-plugin-react-display-name": "2.0.0",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-preset-es2015": "6.6.0",
"babel-preset-es2016": "^6.24.1",
"babel-preset-react": "6.5.0",
"babel-preset-react-hmre": "1.1.1",
"babel-register": "6.8.0",
and webpack.confg.dev.js file is
import webpack from 'webpack';
import path from 'path';
export default {
debug: true,
devtool: 'inline-source-map',
noInfo: false,
entry: [
'eventsource-polyfill', // necessary for hot reloading with IE
'webpack-hot-middleware/client?reload=true', //note that it reloads the page if hot module reloading fails.
path.resolve(__dirname, 'src/index')
],
target: 'web',
output: {
path: __dirname + '/dist', // Note: Physical files are only output by the production build task `npm run build`.
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: path.resolve(__dirname, 'src')
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
{test: /\.js$/, include: path.join(__dirname, 'src'), exclude: /node_modules/, loaders: ['babel','babel-loader']},
{test: /(\.css)$/, loaders: ['style', 'css']},
{test: /\.(jpe?g|gif|svg)$/i, loader: "file-loader?name=/public/icons/[name].[ext]"},
{test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
{test: /\.(woff|woff2)$/, loader: 'url?prefix=font/&limit=5000'},
{test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
{test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'}
]
},
node: {
fs: 'empty',
child_process:'empty'
}
};
i am in just learning phase so any help will be appreciated.
**
the error was that i am using older version of webpack, upgrading it
solved my issue.
**
i think code splitting was not allowed or syntax
import('./someModule.js')
is not allowed in webpack 1.X version
now i have webpack 3.X and error is resolved

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

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)?$/,

Novice at React and Webpack

I'm pretty new to using React with webpack; is this a reasonable config file? What would you add or subtract?
const path = require('path');
const webpackConfig = {
entry: path.resolve(__dirname, 'ENTRY'),
output: {
path: path.resolve(__dirname, 'STATIC'),
filename: 'bundle.js',
},
module: {
loaders: [],
},
resolve: {
extensions: ['.js', '.jsx'],
},
devtool: 'inline-source-map',
};
webpackConfig.module.loaders.push({
test: /\.js[x]?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: { presets: ['es2015', 'react']},
});
webpackConfig.module.loaders.push({
test: /\.(scss|css)$/,
loaders: ['style-loader', 'css-loader', 'sass-loader'],
});
module.exports = webpackConfig;
Also, I'm not entirely sure what dependencies are needed to make this work. There are a few different babel dependencies that have been preloaded into my project folder, but I only see a couple being referenced here (namely, the babel-loader and es2015/react presets).
In my package.json I have
"devDependencies": {
"babel": "^6.23.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-latest": "^6.24.1",
"babel-preset-react": "^6.24.1",
"webpack": "^3.6.0"
},
What you use in your webpack and package.json files is dependent on the needs of your app. For example, if your app handles a lot of images you might want to consider adding a loader that could handle images, such as url-loader. If you want it to handle more dynamic css classes, you might want to add the classNames npm module. So what you have right now works... but it's hard to say what to add without knowing what you're building.
In my personal opinion, I suggest you use create-react-app since you are still new. This way you don't have to deal with configuring your webpack and can focus on the fundamentals of react.

Webpack module parse fails. loader react and babel

I have started with webpack today and I'm having some problems to get it running.
Basically I need an application using react & es6. Bellow you can see the error:
webpack.config.js
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/app.js',
output: {
path: 'dist',
filename: 'bundle.js',
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {
stage: 0
},
include: __dirname + '/app'
},
]
},
plugins: [new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
hash: true,
filename: 'index.html',
inject: 'body'
})]
};
so far what I have tried is install es2015 and configured as
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015']
}
}
but I still getting the same error.
Any idea how can I fix it?
Dependencies
"dependencies": {
"react": "^0.14.0",
"react-dom": "^0.14.2",
"react-redux": "^4.0.0",
"webpack-dev-server": "^1.12.1"
},
"devDependencies": {
"babel-loader": "^5.3.2",
"history": "^1.13.0",
"html-webpack-plugin": "^1.6.2",
"webpack": "^1.12.2"
}
1. npm i babel-core babel-loader babel-preset-es2015 babel-preset-react --save-dev
webpack.config.js should look like this one:
module.exports = {
//.. some stuff before
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loaders: ["babel"],
query: {
presets: ['es2015','react'] // here you can add your stage-0 preset
}
}]
}
//.. some stuff after
}
If you would like to use babel-stage-0 you have to install it throug npm and include stage-0 into `presets' .
And also possible you will find some useful infomation oj this Link
Thanks!

Resources