This article is for those who use ES6 syntax along with Webpack. After I started using Javascript with Webpack I met a lot of unexpected errors. All of them were because of ES6 syntax usage. Those of you who decided to start javascript using "Classes" or you need to use ESlint I'll try to explain how to save some time. In short, it's all about loaders.
Class fields or class properties.
A quite useful feature, isn't it? But the problem is that Webpack doesn't know how to deal with it. Let's look at the example.
The result variable is the class field. After trying to build we get the error.
Now you need to install "babel-loader".
Use
npm install -D babel-loader @babel/core @babel/preset-env webpack
.After the installation process, you need to add this piece of code into you
rules
section of a webpack.config.js
file.
{
test: /\.m?js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env',
{
plugins: ['@babel/plugin-proposal-class-properties'],
},
],
},
}
And the whole file should look similar to this.
That's it. Now you are able to use class fields.
If you use ESlint along with some of the ES6 syntax, then you will have to use babel-eslint.
First, add this command:
npm install eslint babel-eslint --save-dev
Then put this
module.exports = {
parser: "babel-eslint",
};
into your .eslintrc.js file.
That's it! If I knew it before it could have saved a lot of time for me. I hope you found this guide useful. If you have any questions, please let me know in the comments below!