There is a general problem here, that is, the js resource Webpack itself can be processed, why do we still need to deal with it?
The reason is that Webpack has limited processing for js, and can only compile ES modular syntax in js, but cannot compile other syntaxes, which leads to js not being able to run in browsers such as IE, so we hope to do some compatibility processing.
In addition, during the development process, the development team has strict requirements on the code format. The detection of the naked eye is not only limited but also time-consuming and labor-intensive. We need to use professional tools to detect it. Code detection is to use Eslint, and then Babel does the code compatibility processing.
Eslint code detection
Eslint is an assembleable JavaScript and JSX checking tool. In other words, it is a tool used to detect js and jsx syntax, and can configure various functions. We use Eslint, the key is to write the Eslint configuration file, which contains various rules rules. In the future, when Eslint is run, the code will be checked according to the written rules.
Configuration
Its configuration file is written in many ways:
- `.eslintrc.*`:Create a new file,Located in the project root directory - `.eslintrc` - `.` - `.` - The difference is that the configuration format is different - `` middle `eslintConfig`:No need to create a file,Write on the original file
Mainly configure one of the above methods, ESLint will find and automatically read them.
Here we take the `.` configuration file as an example:
= { // parse options parserOptions: {}, // Specific inspection rules rules: {}, // Inherit other rules extends: [], // ... };
For other rules, please refer to the development document:/docs/user-guide/configuring
1.1 parserOptions parserOptions
parserOptions: { ecmaVersion: 6, // ES syntax version sourceType: "module", // ES modular ecmaFeatures: { // Other features of ES jsx: true // If it is a React project, you need to enable jsx syntax } }
1.2 rules Specific rules
- `"off"` or `0` - Close the rules - `"warn"` or `1` - Turn on the rules,Errors using warning level:`warn` (It will not cause the program to exit) - `"error"` or `2` - Turn on the rules,Error using error level:`error` (When triggered,The program will exit) rules: { semi: "error", // Semi-colons are prohibited 'array-callback-return': 'warn', // There is a return statement in the callback function of the array method, otherwise a warning 'default-case': [ 'warn', // Require a default branch in the switch statement, otherwise a warning { commentPattern: '^no default$' } // Allow to comment no default at the end, there will be no warning ], eqeqeq: [ 'warn', // Force use === and !==, otherwise warning 'smart' // /docs/rules/eqeqeq#smart There will be no warning except in a few cases ], }
For other configuration rules, please refer to the development documentation:/docs/rules/
The specific inheritance method is as follows:
= { extends: ["react-app"], rules: { // Our rules will override the react-app rules // So if you want to modify the rules, just change them eqeqeq: ["warn", "smart"], }, };
Use in Webpack
2.1 Download the corresponding plug-in
npm i eslint-webpack-plugin eslint -D
2.2 Defining the configuration file
Create . File:
= { // Inherit Eslint rules extends: ["eslint:recommended"], env: { node: true, // Enable global variables in node browser: true, // Enable global variables in the browser }, parserOptions: { ecmaVersion: 6, sourceType: "module", }, rules: { "no-var": 2, // Cannot use var to define variables }, };
2.3. Modify the configuration file
const path = require("path"); const ESLintWebpackPlugin = require("eslint-webpack-plugin"); //Introduce the Eslint plugin = { entry: "./src/", output: { path: (__dirname, "dist"), filename: "static/js/", // Export the js file to the static/js directory clean: true, // Automatically clear the last packaged directory resources }, module: { rules: [ { // Used to match files ending with .css test: /\.css$/, // The execution order of Loader in the use array is from right to left use: ["style-loader", "css-loader"], }, { test: /\.less$/, use: ["style-loader", "css-loader", "less-loader"], }, { test: /\.s[ac]ss$/, use: ["style-loader", "css-loader", "sass-loader"], }, { test: /\.(png|jpe?g|gif|webp)$/, type: "asset", parser: { dataUrlCondition: { maxSize: 10 * 1024, // Images less than 10kb will be processed by base64 }, }, }, ], }, //Plugin plugins: [ new ESLintWebpackPlugin({ // Specify the root directory of the check file context: (__dirname, "src"), exclude:"node_modules", //Exclude js files in node_module cache:true,//Open cache to improve code checking speed cacheLocation:(__dirname,'../node_modules/.cache/esLintcach'), }), ], mode: "development", };
2.4 Output detection results
Run the following command to view the Eslint check effect in the console
npx webpack
Use in VSCode
Download the Eslint plug-in and you can see the error without compilation. You can solve it in advance. However, at this time, all the files in the project will be checked by default. The files will be reported after packaging in our dist directory. But we only need to check the file below src, not the file below dist.
So you can use Eslint to ignore the file to solve it. Create the following file in the project root directory:
`.eslintignore` ``` # Ignore all files in the dist directorydist ```
Use of Babel
Mainly used to convert code written in ES6 syntax into backwards-compatible JavaScript syntax to be able to run in current and older browsers or other environments
Configuration
Configuration files are written in many ways: - `.*`:Create a new file,Located in the project root directory - `` - `` - `.babelrc.*`:Create a new file,Located in the project root directory - `.babelrc` - `.` - `.` - `` middle `babel`:No need to create a file,Write on the original file
Babel will find and automatically read them, so only one of the above configuration files needs to exist, taking the `` configuration file as an example:
= { // Preset presets: [], };
1.1 presets
Simple understanding: This is a set of Babel plugins that extend Babel functions
- `@babel/preset-env`: A smart preset that allows you to use the latest JavaScript.
- `@babel/preset-react`: A preset for compiling React jsx syntax
- `@babel/preset-typescript`: A preset for compiling TypeScript syntax
2. Babel use in webpack
2.1 Download the corresponding Loader
npm i babel-loader @babel/core @babel/preset-env -D
2.2 Definition of Babel Configuration File
- ```js = { presets: ["@babel/preset-env"], }; ```
2.3 Modify the configuration file
This is actually a new rule to handle js files in the rules configuration:
const path = require("path"); const ESLintWebpackPlugin = require("eslint-webpack-plugin"); //Introduce the Eslint plugin = { entry: "./src/", output: { path: (__dirname, "dist"), filename: "static/js/", // Export the js file to the static/js directory clean: true, // Automatically clear the last packaged directory resources }, module: { rules: [ { // Used to match files ending with .css test: /\.css$/, // The execution order of Loader in the use array is from right to left use: ["style-loader", "css-loader"], }, { test: /\.less$/, use: ["style-loader", "css-loader", "less-loader"], }, { test: /\.s[ac]ss$/, use: ["style-loader", "css-loader", "sass-loader"], }, { test: /\.(png|jpe?g|gif|webp)$/, type: "asset", parser: { dataUrlCondition: { maxSize: 10 * 1024, // Images less than 10kb will be processed by base64 }, }, }, //This is a newly added rule to use Babel compatible js syntax { test: /\.js$/, exclude: /node_modules/, //Exclude node_modules code not to be compiled loader: "babel-loader", }, ], }, //Plugin plugins: [ new ESLintWebpackPlugin({ // Specify the root directory of the check file context: (__dirname, "src"), exclude:"node_modules", //Exclude js files in node_module cache:true,//Open cache to improve code checking speed cacheLocation:(__dirname,'../node_modules/.cache/esLintcach'), }), ], mode: "development", };
2.4 Run commands compatible with js
npx webpack
Open the packaged `dist/static/js/` file and check it, we will find that the arrow function and other ES6 syntax have been converted.
This is the end of this article about Webpack processing js resources (Eslint, Babel). For more related Webpack processing js resources, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!