How to set up webpack to work with React
React is written in es6 so we have to transpile es6 to es5, so we have to use bable. Wabpack uses a concepts ‘loaders‘. Loader is a transformer. We want to install babel-loader that will transform the code. Obviously babel-loader makes use of babel and babel must be configured to use bunch of presets. We need two presets:
- babel preset env to transform es6 to es5
- babel preset react to transform JSX to es5
Let’s install packages
1 |
npm i @babel/core babel-loader @babel/preset-env @babel/preset-react --save-dev |
and to the webpack.config.js add the module
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
module: { rules: [ { test: /\.m?js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env', "@babel/preset-react"] } } } ] } |
We use options to pass presets. We can use a .babelrc file with the code
1 2 3 |
{ "presets": ["@babel/preset-env", "@babel/preset-react"] } |
so that’s it now run npx webpack and and you are able to handle es6 and jsx.
How to watch changes
webpack supports a file watching we can enable it by adding to the webpack.config.js
1 |
watch: true, |
on the whole add such config
1 2 3 4 5 6 7 8 9 |
module.exports = { //... watch: true, watchOptions: { aggregateTimeout: 300, poll: 1000, ignored: [/node_modules/] } } |
you can ignore a lot of files by adding
1 |
ignored: ['files/**/*.js', 'node_modules'] |
to know when it is finished compile in the console use
1 |
npx webpack --watch --info-verbosity verbose |
How to add eslint to webpack
We have to install packages
1 |
npm i babel-eslint eslint eslint-loader eslint-plugin-react |
Then add rule to the webpack.config.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
module: { rules: [ //... { enforce: "pre", test: /\.js$/, exclude: /node_modules/, use: { loader: "eslint-loader", options: { emitWornings: true } } }, //... ] //... |
It should be added after babel. The direction from the bottom to the top. babel should be closer to the top.
Then create an eslint config file .eslintrc and put there the rules
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
{ "extends": [ "eslint:recommended", "plugin:react/recommended" ], "parserOptions": { "ecmaVersion": 6, "sourceType": "module", "ecmaFeatures": { "jsx": true, "modules": true, "experimentalObjectRestSpread": true } }, "plugins": [ "eslint-plugin-react" ], "parser": "babel-eslint", "rules": { "react/jsx-uses-react": "error", "react/jsx-uses-vars": "error", "no-unused-vars": "warn", "no-console": "off", "react/jsx-key": "warn", "react/no-unknown-property": "warn" }, "env": { "browser": true, "node": true, "jasmine": true, }, } |
That’s it, now everything should work.
the end