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.
Related
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
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
})
I added SASS to my project because I like using SASS for my CSS. In my app folder I made CSS folder and a SCSS folder. I run sass --watch scss:css to map over my scss changes to the css folder. This is working great, I think. In my webpack I added a loader to handle SCSS and SASS and added the files need to my package.json. In order to start using the SASS styles do I need to include them in my index.html file or do I need to import them into each component I want to use them with the new es6 import x from 'xpath' thing?
Here are my package.json and webpack.config.js files
{
"name": "newaccount",
"version": "1.0.0",
"description": "a form submission for new accounts",
"main": "App.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "---",
"license": "ISC",
"dependencies": {
"react": "^15.4.1",
"react-dom": "^15.4.1",
"react-hot-loader": "^1.3.1",
"react-router": "^3.0.0"
},
"devDependencies": {
"babel-core": "^6.18.2",
"babel-loader": "^6.2.8",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"css-loader": "^0.26.1",
"html-webpack-plugin": "^2.24.1",
"node-sass": "^3.13.0",
"sass": "^0.5.0",
"sass-loader": "^4.0.2",
"style-loader": "^0.13.1",
"webpack": "^1.13.3",
"webpack-dev-server": "^1.16.2"
}
}
webpack.config.js
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: [
'./app/App.js'
],
output: {
path: __dirname + '/public',
filename: "index_bundle.js"
},
plugins: [HTMLWebpackPluginConfig],
devServer: {
inline:true,
contentBase: './public',
port: 3333
},
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}, {
test: /\.scss$/,
include: path.join(__dirname, "app"),
loaders: ["style", "css", "sass"]
},
{
test: /\.scss$/,
loader: 'style!css!sass'
}]
}
};
My file structure is basically an app folder and a public folder. Inside app you have components / containers / css / scss / utils and inside public is jus the bundle.js and index.html files.
You should not be using an external Sass command with Webpack. You need to put the Sass content in Webpack's dependency graph. To do this, tell Webpack you are using the files, which is done with require(). At the top of your Javascript file for the page needing the style, add
require('./path/to/sass/scss')
In development mode, this will turn your Sass code into Javascript that will inject the built CSS rules into the page. It's strange I know, but it gives you hot reloading of styles. You should also have a separate production build Webpack config using the ExtractTextPlugin to pull the built CSS out into a separate file, and load that file in your production HTML.
Further reading: Webpack: When to Use and Why.
My webpack.config.js file was loading scss and sass twice, changed it to
{
test: /\.scss$/,
loader: 'style!css!sass'
}]
by removing
{
test: /\.scss$/,
include: path.join(__dirname, "app"),
loaders: ["style", "css", "sass"]
},
Now I can include my SASS files in my react components. Now I need to figure out how to access my images inside of my SASS files - seems to toss mass errors =(
I tried all options listed here and other sites but none seem to work.
I was able to install webpack reactjsand other components correctly for my 1st test application (MyApp).
For my next application project, I wanted to leverage all npm-modules from 1st app so that I don't have to download all modules again and keep them centrally.
However, I keep getting above error about missing "es2015". webpack under my 1st app project does not report this problem. The strange thing is even if I change preset from es2015 to say XXes2015, I still get the same message.
My webpack.config.js:
var path = require('path');
var isDev=true;
const cssModulesNames = `${isDev ? '[path][name]__[local]__' : ''}[hash:base64:5]`;
var config = {
entry: path.resolve(__dirname, 'js\\main.js'),
output: {
path: path.resolve(__dirname, '.'),
filename: '.\\bundle.js'
},
resolveLoader: {
modulesDirectories: [ '../../../../Documents/API/react/examples/MyApp/node_modules' ]
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel',
query:
{
presets: [ 'es2015', 'react',"stage-0"]
}
}]
}
};
module.exports = config;
My package.jason:
{
"name": "App1",
"version": "1.13.1",
"description": "",
"main": ".",
"dependencies": {
"babel-core": "latest",
"babel-loader": "latest",
"babel-preset-es2015": "latest",
"babel-preset-react": "latest",
"babel-preset-stage-0": "latest"
},
"devDependencies": {},
"scripts": {
"test": "jest --verbose"
},
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react",
"<rootDir>/node_modules/react-dom",
"<rootDir>/node_modules/react-addons-test-utils",
"<rootDir>/node_modules/fbjs"
]
},
"author": "XX",
"license": "ISC"
}
My .bablrc :
{ "presets": ["es2015", "stage-0", "react"] }
If I change entry es2015 to say esXX2015 in webpack.config.js or .babelrc, it gives same error. I expected it to look for different preset.
Hope someone can throw more light on this and help me out !
Thanks.
make sure your filename is: .babelrc instead of .bablrc
you can try to add babel-loaderon your webpack.config
change loader: 'babel' to loader: 'babel-loader'
Looks like you expect the resolveLoader.modulesDirectories config parameter to tell babel where to find presets. This parameter is used by webpack to find loaders (such as babel-loader), but not by babel.
There is a typo in your question. It should be .babelrc not .bablrc
The content of `.babelrc' should like below. The order is important.
stage-0 → ES2015 → JSX → ES5
{
"presets": [
"stage-0",
"es2015",
"react"
]
}
I suggest you to have presets either in .babelrc file or in webpack.config file to maintain single source of truth. So remove the query entry in your webpack.config and add a exclude entry to ignore js/jsx files from inside the node-modeuls folder (update it as below...)
loaders: [{
test: /\.jsx?$/,
exclude: /node-modules/,
loader: 'babel'
}]
I finally managed to solve the issue by creating node-modules symbolic link to previous projects node_module directory. While this achieved what I wanted, I am bit not happy that various settings in webpack.config.js that I tried could not achieve this. Hope someone comes with right settings, so that webpack behavior is much more clearer ( to me at least). Hope this helps someone else trying to solve similar problem...
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!