Record a nodejs development and use webpack to package and publish the project

Posted by frigidman on Sat, 22 Jan 2022 14:14:47 +0100

Premise: nodejs environment

1. Initialize project

npm init

After the initial project, there will be one more package. In the project directory JSON file, and then the configuration is related to this file

My file directory structure is as follows:

The. babelrc configuration file will be described later

2. Download and configure webpack dependency

After installing webpack, you need to install one more webpack cli,

--save-dev  //Install to development environment
--save      //Production environment dependent use
-g          //Install to global environment

This package is only required for development, so it is installed in the development environment

npm install --save-dev webpack

npm install --save-dev webpack-cli

After installation, package The JSON file devdependences (development environment dependencies) will have more relevant package name and version information

webpack configuration

You need to create a new webpack for webpack in the project directory config. JS file. Next, many configurations will be added to this file, including referencing babel and other plug-ins. This file is not necessary. Without this file, you can also use webpack to package the project. However, in order to unify the location of relevant configuration codes and facilitate packaging, this webpack is newly used config. JS file.

At this time, my project directory structure is as follows:

The simplest webpack config. js :

const path = require('path');

module.exports = {
    mode: 'production',//development and production here means what is the result of webpack packaging. If you choose production, it will be extremely compressed to obtain low storage size and make the code unreadable
    entry: path.resolve(__dirname, "./src/js/demo.js"),  //Entry file
    output: {  
        path: path.resolve(__dirname, './build'),  //Exit path
        filename: "js/demo.min.js"  //Export file name
    }
};

webpack.config.js is a js file with the same syntax as nodejs

module. There are some other keywords exposed by exports. Please understand Baidu by yourself

At this point, you can use the webpack command to package files:

//  Directory / SRC / JS / demo js

//require('../css/demo.css');
const $ = require('./jquery-3.3.1.min.js');

$(document).ready(function(){
    start();
});

function start() {
    console.log("hello world")
}

nodejs itself can import other js plug-ins, but css files can't be imported directly and packaged. webpack can't recognize it

Next, we will introduce how to import css with js and then package it with webpack

3. Download and configure style loader and CSS loader package dependencies

loader enables webpack to handle non JavaScript files (webpack itself only understands JavaScript). loader can convert all types of files into effective modules that webpack can handle, and then you can use the packaging ability of webpack to process them.

Installation dependency

npm install style-loader css-loader --save-dev
"devDependencies": {
    "css-loader": "^5.2.6",
    "style-loader": "^3.0.0",
    "webpack": "^5.41.1",
    "webpack-cli": "^4.7.2"
  }

Configure webpack config. js

In webpack config. Rules for adding JS files:

const path = require('path');

module.exports = {
    mode: 'production',//development,production
    entry: path.resolve(__dirname, "./src/js/demo.js"),
    output: {
        path: path.resolve(__dirname, './build'),
        filename: "js/demo.min.js"
    },
    module: {
        rules:[
            {
                test: /\.css$/,
                use: [ 'style-loader', 'css-loader' ]
                // test shows what types of files the current loader can handle
                // use specifies the type of loader.
                // Note: the loader in the array cannot omit the extension
            }
        ]
    },
};

Then you can import css files into js files and package them together:

//  Directory / SRC / JS / demo js

require('../css/demo.css');
const $ = require('./jquery-3.3.1.min.js');

$(document).ready(function(){
    start();
});

function start() {
    console.log("hello world")
}

4. Download and compile with babel

At present, the syntax of ES6(ES2015) has been applied on a large scale. It has the characteristics of more concise and more powerful functions. Modules using ES6 syntax are likely to be used in actual projects, but the browser's support for ES6 syntax is not perfect. In order to achieve compatibility, you need to use the conversion tool to convert ES6 syntax to ES5 syntax. babel is the most commonly used tool

Installation dependency

npm install babel-loader @babel/core @babel/preset-env --save-dev
  "devDependencies": {
    "@babel/core": "^7.14.6",
    "@babel/preset-env": "^7.14.7",
    "babel-loader": "^8.2.2",
    "css-loader": "^5.2.6",
    "style-loader": "^3.0.0",
    "webpack": "^5.41.1",
    "webpack-cli": "^4.7.2"
  }

In webpack config. Add rules to JS file:

const path = require('path');

module.exports = {
    mode: 'production',//development,production
    entry: path.resolve(__dirname, "./src/js/demo.js"),
    output: {
        path: path.resolve(__dirname, './build'),
        filename: "js/demo.min.js"
    },
    module: {
        rules:[
            {
                test: /\.css$/,
                use: [ 'style-loader', 'css-loader' ]
                // test shows what types of files the current loader can handle
                // use specifies the type of loader.
                // Note: the loader in the array cannot omit the extension
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ['babel-loader']
            }
        ]
    },
};

Then create a new one babelrc file, that is, the file I created earlier, writes:

Please refer to Baidu for specific field meanings

{
    // "presets":[
    //     "@babel/preset-env"
    // ],
    "presets": [
        ["@babel/preset-env", {
          "targets": {
            "browsers": [ "ie >= 8", "chrome >= 62" ]
          }      
        }]
    ],
    "plugins":[]
}

At this point, packaging with the webpack command will be automatically compatible with the es5 syntax environment

5. Download and install URL loader to reduce the number of http requests

Converting image files to base64 encoding and loading them into the browser can reduce the number of http requests, but increase the volume of js or html files. If images are highly reused in the project, base64 encoding will be generated for each reference, resulting in code redundancy. The files loaded into the browser through http request can be cached locally. When the reuse of pictures in the project is high, it will increase the convenience of caching for picture access and make the next access faster. Therefore, it should be balanced.

Install URL loader, including URL file

npm install --save-dev url-loader
  "devDependencies": {
    "@babel/core": "^7.14.6",
    "@babel/preset-env": "^7.14.7",
    "babel-loader": "^8.2.2",
    "css-loader": "^5.2.6",
    "style-loader": "^3.0.0",
    "url-loader": "^4.1.1",
    "webpack": "^5.41.1",
    "webpack-cli": "^4.7.2"
  }

Configure webpack config. JS file} adding rules:

const path = require('path');

module.exports = {
    mode: 'production',//development,production
    entry: path.resolve(__dirname, "./src/js/demo.js"),
    output: {
        path: path.resolve(__dirname, './build'),
        filename: "js/demo.min.js"
    },
    module: {
        rules:[
            {
                test: /\.css$/,
                use: [ 'style-loader', 'css-loader' ]
                // test shows what types of files the current loader can handle
                // use specifies the type of loader.
                // Note: the loader in the array cannot omit the extension
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ['babel-loader']
            },
            {// Implement url resource packaging
                // Image files are processed using URL loader
                test: /\.(png|jpg|gif|ttf|eot|woff|woff2|svg)$/,
                use: [
                    {
                        loader: 'url-loader',
                        // Options are configurable options
                        options: {
                            limit: 8192
                            // limit=8192 means that all pictures less than 8kb are converted to base64 format
                            // (in fact, it should be said that only those over 8kb use URL loader to map to the file, otherwise it will be converted to the form of data url)
                        }
                    }
                ]
            }
        ]
    },
};

6. Download and install HTML webpack plugin to automatically generate an HTML file

html webpack plugin will automatically generate an html file for you according to the specified index The html template generates the corresponding html file.

Installation dependency

npm install html-webpack-plugin --save-dev
  "devDependencies": {
    "@babel/core": "^7.14.6",
    "@babel/preset-env": "^7.14.7",
    "babel-loader": "^8.2.2",
    "css-loader": "^5.2.6",
    "html-webpack-plugin": "^5.3.2",
    "style-loader": "^3.0.0",
    "url-loader": "^4.1.1",
    "webpack": "^5.41.1",
    "webpack-cli": "^4.7.2"
  }

Configure webpack config. JS file} adding rules:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'production',//development,production
    entry: path.resolve(__dirname, "./src/js/demo.js"),
    output: {
        path: path.resolve(__dirname, './build'),
        filename: "js/demo.min.js"
    },
    module: {
        rules:[
            {
                test: /\.css$/,
                use: [ 'style-loader', 'css-loader' ]
                // test shows what types of files the current loader can handle
                // use specifies the type of loader.
                // Note: the loader in the array cannot omit the extension
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ['babel-loader']
            },
            {// Implement url resource packaging
                // Image files are processed using URL loader
                test: /\.(png|jpg|gif|ttf|eot|woff|woff2|svg)$/,
                use: [
                    {
                        loader: 'url-loader',
                        // Options are configurable options
                        options: {
                            limit: 8192
                            // limit=8192 means that all pictures less than 8kb are converted to base64 format
                            // (in fact, it should be said that only those over 8kb use URL loader to map to the file, otherwise it will be converted to the form of data url)
                        }
                    }
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./src/index.html",
            filename: "webpack.html",  //Index. In the src directory Generate a packaged webpack.html for the template HTML to build directory
            minify: {
                minimize: true, //Package as minimum
                removeAttributeQuotes: false,  //Remove quotation marks
                removeComments: true,  //Remove comments
                collapseWhitespace: true,  //Remove spaces
                minifyCSS: true,  //Compress styles within html
                minifyJS: true, //Compress js in html
                removeEmptyElements: false //Clean up elements with empty content
            },
            hash: true  //Add hash when introducing output resources to avoid caching
        })
    ]
};

At this time, using the webpack command will generate in the build directory:

7. Download and install the copy webpack plugin package and copy other files not packaged by webpack to the specified directory

This can ensure the reference relationship between the packaged html and the html file before packaging relative to the whole project file (the original static folder is copied to the automatically generated html folder, and the hierarchical relationship is consistent with the original)

Installation package dependency

npm install --save-dev copy-webpack-plugin
  "devDependencies": {
    "@babel/core": "^7.14.6",
    "@babel/preset-env": "^7.14.7",
    "babel-loader": "^8.2.2",
    "copy-webpack-plugin": "^9.0.1",
    "css-loader": "^5.2.6",
    "html-webpack-plugin": "^5.3.2",
    "style-loader": "^3.0.0",
    "url-loader": "^4.1.1",
    "webpack": "^5.41.1",
    "webpack-cli": "^4.7.2"
  }

Configure webpack config. JS file} adding rules:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
    mode: 'production',//development,production
    entry: path.resolve(__dirname, "./src/js/demo.js"),
    output: {
        path: path.resolve(__dirname, './build'),
        filename: "js/demo.min.js"
    },
    module: {
        rules:[
            {
                test: /\.css$/,
                use: [ 'style-loader', 'css-loader' ]
                // test shows what types of files the current loader can handle
                // use specifies the type of loader.
                // Note: the loader in the array cannot omit the extension
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ['babel-loader']
            },
            {// Implement url resource packaging
                // Image files are processed using URL loader
                test: /\.(png|jpg|gif|ttf|eot|woff|woff2|svg)$/,
                use: [
                    {
                        loader: 'url-loader',
                        // Options are configurable options
                        options: {
                            limit: 8192
                            // limit=8192 means that all pictures less than 8kb are converted to base64 format
                            // (in fact, it should be said that only those over 8kb use URL loader to map to the file, otherwise it will be converted to the form of data url)
                        }
                    }
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./src/index.html",
            filename: "webpack.html",  //Index. In the src directory Generate a packaged webpack.html for the template HTML to build directory
            minify: {
                minimize: true, //Package as minimum
                removeAttributeQuotes: false,  //Remove quotation marks
                removeComments: true,  //Remove comments
                collapseWhitespace: true,  //Remove spaces
                minifyCSS: true,  //Compress styles within html
                minifyJS: true, //Compress js in html
                removeEmptyElements: false //Clean up elements with empty content
            },
            hash: true  //Add hash when introducing output resources to avoid caching
        }),
        new CopyWebpackPlugin({
            patterns: [
                { from: __dirname+'/src/assets', to: __dirname+'/dist/assets' },
            ],        
        })
    ]
};
Use at this time webpack

The static resource directory will be copied to the final release product directory

This is the index html   demo.js and in demo JS imported files will be packaged and compressed, and other static project files will also be copied to the publishing directory, so that the url of the static resource file introduced by HTML after packaging and publishing will not make mistakes. Finally, as long as the build directory is published, the published files do not need nodejs environment support.

Reference link: webpack packaging path change_ Webpack packaging tutorial

Reference link: copy webpack plugin

Reference link: Webpack Getting Started tutorial

Reference link: webpack4 configuration - 19: introduction of third-party plug-in Libraries

Reference link: webpack plug-in URL loader usage specification

Reference link: URL loader

Topics: Javascript node.js ECMAScript Webpack html