background

Manually configure a WebPack5 project as webPack5 + vue3 + Babel + TypeScript + ESLint + stylelint

This is my Github repository learning-Webpack5 for reference

The installation

webpack

npm i webpack@5.44. 0 webpack-cli@4 webpack-manifest-plugin webpack-merge -D
Copy the code
const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
const { merge: webpackMerge } = require('webpack-merge');
const baseConfig = require('./base.js');

module.exports = webpackMerge(baseConfig, {
  plugins: [
    new WebpackManifestPlugin({
        publicPath: ' '.filter: function (FileDescriptor) {
            returnFileDescriptor.isChunk; }})]})Copy the code

webpack-dev-server

npm install webpack-dev-server@4 -D

Note that in webpack5, the command to start the service is no longer webpack-dev-server — config. /build/dev.js

Instead, use the new command webpack serve — config. /build/dev.js

module.exports = {
  devServer: {
    host: '... '.port: 8087./* Port number */
    compress: true./* Enable gzip compression */
    open: [`http://localhost:${server.port}`]./* Tell dev-server to open the browser after the server has started */
    hot: true./* Enable webpack hot module replacement */
    client: {
        progress: true./* Displays compilation progress as a percentage in the browser */
        overlay: {
            errors: true.warnings: false,},/* Displays full screen coverage in the browser when compilation errors or warnings occur */
    },
    /* Provides the ability to execute custom middleware before all other middleware executes inside the server. This can be used to define custom handlers */
   /* I have a multi-page application configured, so I added this, normal does not need to add this */
    onBeforeSetupMiddleware: function (devServer) {
        if(! devServer) {throw new Error('webpack-dev-server is not defined');
        }
        devServer.app.get('/'.(req, res) = > {
            var resHtml = ` 
         
       index   
      
    `
; for (let key in entries) { if (key.indexOf('\/commons\/') = = = -1) { resHtml += `<li><a href="${key}.html">${key}.html</a></li>`; } } resHtml += ` `; res.send(resHtml); }); }, onListening: function (devServer) { if(! devServer) {throw new Error('webpack-dev-server is not defined'); }}}}Copy the code

Turn ES6 ES5

npm i babel-loader @babel/core @babel/preset-env -D

npm install @babel/plugin-transform-runtime -D
npm install  @babel/runtime @babel/runtime-corejs3 --save
Copy the code
// .babelrc
{
    "presets": [["@babel/preset-env",
            {
                "targets": {
                    "browsers": ["1%" >."last 2 versions"."not ie <= 8"."Android > = 4.4"]}}]],"plugins": [["@babel/plugin-transform-runtime", {
            "corejs": 3}}]]Copy the code
// loader
module.exports = {
  module: {
    rules: [{test: /\.js$/,
        exclude: file= > (
            /node_modules/.test(file) &&
            !/\.vue\.js/.test(file)
        ),
        use: [
            'babel-loader']},]}}Copy the code

loader

Processing style

Since WebPack can only handle commonJS files, you need to use a different loader to handle other files

npm install vue-style-loader style-loader css-loader postcss-loader sass sass-loader autoprefixer -D

html

npm install html-loader -D

Creating an HTML file

npm install html-webpack-plugin -D

Clear packaged files

npm i clean-webpack-plugin -D

Processing pictures and other documents

There is no need to install file-loader and url-loader, webpack5 is built in

Url-loader: When a file reaches a certain size, it can be processed as a Base64 URIS with built-in file-loader

Webpack5: Provides built-in static resource building capabilities, so url-loader does not need to be installed

// WebPack5 has a built-in loader
module.exports = {
    module: {
        rules: [{test: /\.(jpe? g|png|gif|svg)$/i,
                type: 'asset'.generator: {
                    // [ext] comes with a "."
                    filename: 'assets/[name].[hash:7][ext]'}}]}}Copy the code

The environment variable

Environment variables are set as cross-env because they can be set across terminals

npm install cross-env -D

// command
cross-env NODE_ENV=development
Copy the code

yargs

Gets command line arguments

npm i yargs@13 -D

Getting environment variables

yargs@13 const argv = require(‘yargs’).argv; yargs@13 const argv = require(‘yargs’).argv; To obtain parameters

chokidar

I don’t need that for now

Chokidar can be used to monitor file and folder changes

npm i chokidar --save-dev

Packing compression

Extract CSS files & Compress CSS

npm install mini-css-extract-plugin css-minimizer-webpack-plugin -D

The mini – CSS – extract – the plugin making address

Compress CSS

Notice, use a different one

Use csS-minimizer-webpack-plugin —- css-minimizer-webpack-plugin

Optimize – CSS -assets-webpack-plugin —- optimize- CSS -assets-webpack-plugin

// Extract the CSS file
new MiniCssExtractPlugin({
    // filename: path.resolve(__dirname, 'dist/css/index.css')
    filename: 'css/[name].[contenthash:7].css'
})
/ / compress CSS
new OptimizeCssAssetsWebpackPlugin()
Copy the code

Compression JS

npm install terser-webpack-plugin -D

const TerserPlugin = require('terser-webpack-plugin');

optimization: {
    minimize: true.minimizer: [
        new TerserPlugin()
    ]
},
Copy the code

ESlint & stylelint

stylelint-webpack-plugin

typescript

npm install typescript ts-loader -D

[email protected]

npm install vue@next -S
npm install vue-loader@next @vue/compiler-sfc -D
Copy the code

postcss-loader

Github.com/webpack-con…

Function:

  1. Parse CSS into an AST abstract syntax tree
  2. Call the plug-in, work with the abstract syntax tree, and add functionality

webpack-manifest-plugin

Github.com/shellscape/…

const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
const options = { ... };

module.exports = {
  plugins: [
    new WebpackManifestPlugin(options)
  ]
};

Copy the code

optimization

// Tell Webpack which algorithm to use when selecting a module ID
optimization: {
    moduleIds: 'deterministic' // The name of the bit value module that is hashed to.
},
Copy the code

The environment to support

Node V10.13.0 or later

The resources

Juejin. Cn/post / 692418…

Github.com/zxpsuper/cr…

Chinese website