Webpack packaging

Webpack creates a webpack.config.js file in the project root directory

webpack.config.js

There are five main attributes

module.exports = {
    entry:"".output: {filename:"".// The name of the output file
        path:"" // The location of the output file
    },
    module: {rules: {text:'Regular expressions'.// Process the matched files
            exclude:"".// Process files that are not matched
            exclude: /node_modules/.// Exclude files under the node_modules file
            use:[ // Execute from bottom to top and from right to left
                'css-loader',
                { // To configure a loader in detail
                   loader:"postcss-loader".options: {}}],// Use this property when using a loader
            loader:"".// Use this if only one loader is used
            enforce:"pre".// If there are multiple Loaders processing this means that this loader is executed first
            // If there is only one loader, you can directly configure it using options
            options: {}}}.// How to load files in different formats
    plugins: [].// Load different plug-ins
    mode:""./ / environment (development | | production)
    // This is a service used to generate temporary files
    // Need to install webpack-dev-server
    // Command: NPM I webpack-dev-server -d
    // DevServer: for automation
    // Features: it is only compiled and packaged in memory with no output
    // Start devServer with the NPX webpack-dev-server directive
    devServer: {contentBase:resolve(__dirname, 'built'),
        // Start GZIP compression
        compress:true./ / the port number
        port:3000.// Open the browser automatically
        open:true}}Copy the code

The following is the image of the package CSS less HTML font file

CSS required loader

Style – loader, CSS – loader

module: {
    rules: [{
        test: /\.css$/,
        use: [
            'style-loader'.'css-loader',].}},]Copy the code

Less the loader

The style-Loader, CSS-Loader, and less-Loader plug-ins must be installed first

module: {
    rules: [{
        test: /\.css$/,
        use: [
            'style-loader'.'css-loader'.'less-loader',].}},]Copy the code

Font files and images required loader

File – loader, url – loader

module: {
    rules: [{test: /\.(jpg|png|gif|jpe1g)$/,
                use: [{
                    loader: "file-loader".options: {
                    // Base64 will process images smaller than 8KB
                    // Advantage: can reduce the number of requests
                    // Yes: the image size will be larger
                    limit:102400.// Configure esModule: false when [Object Module] appears during parsing
                    // name: utils.assetsPath('img/[name].[hash:7].[ext]'),
                    // outputPath: "media/" can output files to a fixed directory}}, {/ / exclude: / \ | js | | HTML, CSS JPG | PNG | | GIF jpeg) $/, here refers to exclude these format files
                test: /\.ttf$/,
                use: [{
                    loader: "file-loader".options: {
                        name: "[hash:4].[ext]".outputPath: "media/"}}]}],},]}Copy the code

HTML required loader

html-loader

Output with an HTML file as a template

html-webpack-plugin

npm i html-webpack-plugin -D
Copy the code
const HtmlWebpackPlugin = require("html-webpack-plugin")
plugins: [new HtmlWebpackPlugin({
            template: "./index.html".minify: {// Remove Spaces
                collapseWhitespace:true.// Remove comments
                removeComment:true}}),]Copy the code

Extract CSS into individual files

This plugin allows the CSS to be exported separately to the mini-css-extract-plugin

npm i mini-css-extract-plugin -D
Copy the code
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const commonCssLoader = [
    MiniCssExtractPlugin.loader,
    'css-loader',]module: {
    rules: [{
            test: /\.css$/,
            use: [
                ...commonCssLoader,
            ]
        },
        {
            test: /\.less$/,
            use: [
                ...commonCssLoader,
                'less-loader',]},}},plugins: [new MiniCssExtractPlugin({
        // Rename the output file
        filename:"css/built.css",})]Copy the code

CSS compatibility

npm i postcss-loader postcss-preset-env -D

For postCSS, find the configuration of browserslist in package.json and load the specified CSS compatibility style through the configuration

const commonCssLoader = [
    MiniCssExtractPlugin.loader,
    'css-loader'.// CSS compatibility requires defining browserslist in package.json
    /* "browserslist": { "development": [ "last 1 chrome vesion", "last 1 firefox vesion", "last 1 safari vesion" ], "production": [">0.2%", "not dead", "not op_mini all"]}*/
    {
        loader: "postcss-loader".options: {
            postcssOptions: {
                plugins: [['postcss-preset-env',
                        {
                            ident: "postcss"},],],}}}]rules: [{
    test: /\.css$/,
    use: [
        ...commonCssLoader,
    ]
},
{
    test: /\.less$/,
    use: [
        ...commonCssLoader,
        'less-loader',]},]Copy the code
package.json
"browserslist": {// Set nodejs environment variable;
    // process.env.NODE_ENV = 'devlopment';
    // Development environment = set the node environment variable: process.env.node_env = devlopment
    "development": ["last 1 chrome vesion".// Compatible with the latest Chrome
        "last 1 firefox vesion".// Compatible with the latest Firefox
        "last 1 safari vesion".// Compatible with the latest Safari]."production": ["0.2%" >."not dead"."not op_mini all"]}Copy the code

Compress CSS

optimize-css-assets-webpack-plugin

npm i optimize-css-assets-webpack-plugin -D
Copy the code
const optimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin")
plugins: [new optimizeCssAssetsWebpackPlugin()
]
Copy the code

Js compatibility processing

1. Js compatibility processing: babel-loader@babel /preset- env@babel /core still does not support promises

Import “@babel/polyfill” import “@babel/polyfill”

3, need to do compatibility processing do: on demand processing — “core-JS

If you want to use the import “@babel/polyfill”, you can delete the import “@babel/polyfill”. Generally, 1 and 3 are used in combination with babel-loader@babel /preset-env @babel/core @babel/polyfill

module: {rules:[
            {
                test:/\.js$/,
                exclude:/node_modules/,
                loader:"babel-loader"Options: {// Presets: indicate how Babel should handle compatibility
                    // presets:['@babel/preset-env']
                    presets:[
                       [
                            '@babel/preset-env',
                            {
                                // Load on demand
                                useBuiltIns: 'usage'.// Specify the core-js version
                                corejs: {
                                    version: 3
                                },
                                targets: {
                                    chrome: "60".firebox: "60".ie:'9'.safari: '10'}}]}}Copy the code

Set esLint syntax validation using Airbnb

Required plugin eslint eslint-config-Airbnb-base eslint-loader eslint-plugin-import

{
    test: /\.js$/,
    exclude: /node_modules/.// Execute first
    enforce: "pre".loader: "eslint-loader".options: {
        // Auto-fix the JS syntax specification
        fix: true}},Copy the code

Add in package.json

"eslintConfig": {
    "extends": "airbnb-base"
}
Copy the code

The complete file

{
    test: /\.html$/.// Process the img image in the HTML file
    loader: "html-loader"
},
Copy the code
const {
    resolve
} = require("path");

process.env.NODE_ENV = 'production'; // The packing environment


const MiniCssExtractPlugin = require('mini-css-extract-plugin'); / / compress CSS

const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin"); // CSS compatibility

const HtmlWebpackPlugin = require("html-webpack-plugin"); / / HTML plugin

const commonCssLoader = [
    MiniCssExtractPlugin.loader,
    'css-loader'.// CSS compatibility requires defining browserslist in package.json
    /* "browserslist": { "development": [ "last 1 chrome vesion", "last 1 firefox vesion", "last 1 safari vesion" ], "production": [">0.2%", "not dead", "not op_mini all"]}*/
    {
        loader: "postcss-loader".options: {
            postcssOptions: {
                plugins: [['postcss-preset-env',
                        {
                            ident: "postcss"},],],}}}]module.exports = {
    entry: './index.js'.output: {
        filename: 'js/built.js'.path: resolve(__dirname, 'built')},module: {
        rules: [{
                test: /\.css$/,
                use: [
                    ...commonCssLoader,
                ]
            },
            {
                test: /\.less$/,
                use: [
                    ...commonCssLoader,
                    'less-loader',]},/ * normally A file can only be a loader When a file is going to be multiple loader, so be sure to make loader order of execution To perform again eslint Babel can add an attribute to one of the loader enforce: "pre" * /
            // js set esLint syntax validation to use Airbnb
            /* Add "eslintConfig": {"extends": "airbnb-base"} */
            / / {
            // test: /\.js$/,
            // exclude: /node_modules/,
            // // Priority
            // enforce: "pre",
            // loader: "eslint-loader",
            // options: {
            // // automatically fixes the JS syntax specification
            // fix: true
            / /}
            // },
            // js compatibility processing
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: "babel-loader".options: {
                    presets: [['@babel/preset-env'.// 1. The compatibility part of the syntax does not include promise
                            Import "@babel/polyfill" import "@babel/polyfill" import "@babel/polyfill"
                            // 3, "@babel/polyfill" can be deleted after core-js is used
                            // This is 1 and 3
                            {
                                // Load on demand
                                useBuiltIns: 'usage'.// Specify the core-js version
                                corejs: {
                                    version: 3
                                },
                                targets: {
                                    chrome: "60".firefox: "60".ie: '9'.safari: '10'.edge: '17'}}]]}},/ / {
            // test: /\.(jpg|png|gif|jpeg)$/,
            // loader: 'url-loader',
            // options: {
            // limit: 8 * 1024,
            // name: "[hash:10].[ext]", // Image name
            // outputPath: 'imgs', // Image output directory
            // esModule: false, // prevent HTML directly referenced image link error
            / /}
            // },
            {
                test: /\.html$/,
                loader: "html-loader",},/ / {
            // exclude: /\.(jpg|png|gif|jpeg|html|js|less|css)$/,
            // loader: 'file-loader',
            // options: {
            // outputPath: 'media', // The output directory of these files
            / /}
            // }]},plugins: [
        new MiniCssExtractPlugin({
            filename: "css/built.css".// Remove CSS from JS
        }),
        new OptimizeCssAssetsWebpackPlugin(), / / compress CSS
        new HtmlWebpackPlugin({
            template: "./index.html".// The output template file
            minify: {
                HTML / / compression
                collapseBooleanAttributes: true.// Remove comments
                removeComments: true,}})],mode: "production"
}
Copy the code

package.json

{
  "name": "webpackcs"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": []."author": ""."license": "ISC"."dependencies": {
    "jquery": "^ 3.6.0"
  },
  "devDependencies": {
    "@babel/core": "^ 7.14.8"."@babel/preset-env": "^ 7.14.8"."babel-loader": "^ 8.2.2"."css-loader": "^ 6.0.0"."eslint": "^ 7.31.0"."eslint-config-airbnb-base": "^ 14.2.1." "."eslint-loader": "^ 4.0.2." "."eslint-plugin-import": "^ 2.23.4"."file-loader": "^ 6.2.0"."html-loader": "^ 2.1.2"."html-webpack-plugin": "^ 5.3.2." "."less": "^ 4.4.1"."less-loader": "^ 10.0.1." "."mini-css-extract-plugin": "^ 2.1.0." "."optimize-css-assets-webpack-plugin": "^ the 6.0.1." "."postcss-loader": "^ 6.1.1." "."postcss-preset-env": "^ 6.7.0"."style-loader": "^ 3.1.0"."webpack": "^ 5.44.0"."webpack-cli": "^" 3.3.12."webpack-dev-server": "^ 3.11.2"
  },
  "browserslist": {
    "development": [
      "last 1 chrome vesion"."last 1 firefox vesion"."last 1 safari vesion"]."production": [
      "0.2%" >."not dead"."not op_mini all"]}},"eslintConfig": {
    "extends": "airbnb-base"
}

Copy the code