Continue to fill the Webpack pit today. After webpack5 compiled and processed CSS files last time, today we will talk about how Webpack5 handles JS files.
The target
- Compile ES6
- The introduction of eslint
- Compressed JS files
- Introducing global variables
Knowledge point brain map
The code used in the project
Github.com/joychenke/w…
Compile ES6
Compiling ES6 syntax is implemented through Babel.
-
Install Babel yarn add Babel -loader @babel/ core@babel /preset-env -d
-
@babel/core is the core NPM package that uses Babel for transcoding. Babel-cli and babel-node depend on this package
-
@babel/ Preset -env is a Babel prefab kit containing every possible translation tool
-
-
Add the Babel configuration to webpack.config.js module, rules. Note the addition of includes. Only js files in the SRC folder are processed
{
test: /\.js$/.// Matches the js file
use: ['babel-loader'].include: path.resolve(__dirname, 'src')}Copy the code
- Add a. Babelrc file to configure Babel
{
"presets": [
"@babel/preset-env"]."plugins": []}Copy the code
- After using the above configuration, I still cannot use async await. Online found the following, need to install
@babel/plugin-transform-runtime
Can only be - The installation
@babel/plugin-transform-runtime
,yarn add @babel/runtime @babel/plugin-transform-runtime
- Modify the
.babelrc
Transform-runtime file. At this point async await can be used.
{
"presets": [
"@babel/preset-env"]."plugins": [
"@babel/plugin-transform-runtime"]}Copy the code
Install @babel/runtime dependencies in dependencies. The @babel/plugin-transform-runtime runtime dependencies are dependencies that you install in devDependencies only.
Add eslint-Loader formatting code
- Install ESLint and eslint-Loader
yarn add eslint eslint-loader -D
- Configure babel-loader in webpack.config.js
{
test: /\.js$/.// Matches the js file
use: ['babel-loader',
{
loader: 'eslint-loader'.options: {
enforce: 'pre' // Pre-loader, Webpack takes precedence}}].include: path.resolve(__dirname, 'src')},Copy the code
- Add.eslintrc.json in the root directory. The file is obtained from cn.eslint.org/demo/, which is downloaded from demo on the official website
- After completing the above steps, it will be found that the project is reported wrong and there are three problems
/ / the problem 1
moduleIs not defined2 / / problem
constIs a reserved word3 / / problem
ESLint Parsing error: Unexpected token
Copy the code
- The solution to problems 1 and 2 is to configure ESLint to support ES6 and Node syntax. Problem 3 is the introduction of babel-esLint. Install babel-esLint first and then modify.eslintrc.json
/ / install Babel - eslint
yarn add babel-eslint -D
/ / modify. Babelrc. Json{...// Other configurations
"env": {
"es6": true."node": true
},
"parser": "babel-eslint"
}
Copy the code
- Restart the service NPM run dev and esLint is configured
Compressed JS files
- Terser-webpack-plugin is a plugin used to compress JS
- Configuring this plug-in
const TerserWebpackPlugin = require('terser-webpack-plugin')
optimization: {
minimizer: [
new OptimizeCssAssetsWebpackPlugin(),
new TerserWebpackPlugin()
]
}
Copy the code
- Repackage the NPM Run build. Js files can be compared before compression and after compression, significantly smaller.
Introducing global variables
Some plug-ins are required by many components, such as jquery, and it is convenient and necessary to introduce a global attribute $pointing to the jquery object. There are two ways to introduce global objects: 1.ProvidePlugin 2. Expose-loader Here’s how to inject global variables in each of these ways.
- Global register jQuery
- Install jQuery globally,
yarn add jquery
- Global properties are introduced using the ProvidePlugin provided with the WebPack module
$
To point tojquery
object
// Introduce the Webpack module
const Webpack = require('webpack')
// Add the following code to plugins in webpack.config.js
new Webpack.ProvidePlugin({
$: 'jquery' // Add jQuery to the global variable
})
Copy the code
- Restart the service and you will find an error
'$' is not defined no-undef
- This error is reported by ESLint. The global variable jquery or $needs to be declared. Modify. Eslintrc. Json. Then restart the service. (Modification of.eslintrc.json requires manual restart to take effect.)
// The following two methods are valid
// Add jquery to env: true
"env": {
"es6": true."node": true."jquery": true
},
// Add globals to the env level
"globals": {
"$": true
},
Copy the code
- That’s through
webpack.ProvidePlugin
To inject global variables, you can also useexpose-loader
Add global variables. Before we start the demo, let’s resolve the issue of how import and require are compatible in index.js. Modify.eslintrc.json and restart the service
{...// Other attributes
"parserOptions": {
"ecmaVersion": 2020."sourceType": "module".// Other attributes},...// Other attributes
}
Copy the code
The following uses dayjs as an example to explain how to use expose-loader to import global variables. Install dayjs YARN add day.js.
expose-loader
Is inline loader, can be used in inline mode, can also be used in webpack.config.js configuration mode. Let’s start with inline use
1.Write the following code in the info.js file. That is to`$day`Add to the global object named $dayimport $day from "expose-loader? exposes=$day! dayjs"
2.In files that need to use day.js, just use $dayconst time = $day().format('YYYY-MM-DD')
console.log(time)
Copy the code
- After the preceding configuration is complete, restart the service, and an error message is displayed
'$day is not defined no-undef
. Eslint reported an error and needs to add a configuration in ESLint to name the following global attribute $day
"globals": {
"$day": true
},
Copy the code
expose-loader
In addition to being used in components, it can be used inwebpack.config.js
In the. You can refer to the official website for instructionsWebpack.docschina.org/loaders/exp…, the specific implementation is divided into two steps: 1. Configure expose-loader in webpack 2. In the top-level JS configurationimport $day from "dayjs"
// step1: configure expose-loader in webpack
{
The require.resolve call is a Node.js function that gives the absolute path to the module
test: require.resolve('dayjs'),
loader: 'expose-loader'.options: {
exposes: ['$day']}},// step2: introduce dayjs in the first js file executed
import $day from "dayjs"
Copy the code
conclusion
Today about Webpack5 to JS processing is introduced here, later will continue to update Webpack5 compile and package image files