preface

Two days ago, Lao Asked me to review the use of Webpack. He wanted to realize webpack separately for JS, CSS and files, similar to the effect of vue.config.js package. I went to see some tutorials, can achieve the function you want, this article does not do about the introduction of Webpack, mainly to achieve packaging function.

This article will show you how to use WebPack. Since webpack5 is used, errors are often reported when using it improperly, and it is quite a mind-boggling thing to see a lot of errors. Some cautions and potholes are also mentioned.Copy the code

Initialization Process

1, install,

Create a new folder webpack_project and use NPM init -y to quickly generate package.json

{" name ":" webpack_project ", "version" : "1.0.0", "description" : ""," main ":" index. Js ", "scripts" : {" test ": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }Copy the code

NPM isntall webpack webpack-cli –save-dev NPM isntall webpack webpack-cli –save-dev Here the author uses –save-dev. Since webpack-CLI may be used later, it is installed here first, and will be explained if it is used later. Once installed, a devDependencies dependency is generated in the package.json file, which shows the dependencies you just downloaded.

"devDependencies": {
    "webpack": "^ 5.52.1"."webpack-cli": "^ 4.8.0"
  }
Copy the code

2. Create project folders and configure them

Create a new SRC folder in the root directory for your development files, and create an index.js folder in the SRC folder. The index.js folder is the package entry file. Then create a new webpack.config.js file in the root directory. This file is the package configuration for the entire project, and some rules are configured in this file.

Now we can add the configuration code to the webpack.config.js file

Module. Exports = {mode: 'development', // Development mode entry: Output: {filename: 'index.js', // output filename}}Copy the code

Set mode to development mode. Js files packaged in this mode will not be compressed. Entry is the entry for packaging, and output is the configuration of output. Here we can also go to the official webPack documentation

Next we add the startup command under scripts of package.json

"scripts": {
    "build": "webpack"
  },
Copy the code

To package the project, run the NPM run build command

You can see that a dist folder is generated in the root directory, and the index.js file in the root directory is the index.js file packaged in SRC. Here we can see that when you configure the output file, if you only configure the output file name, it will be packaged as a dist folder by default. You can also specify the output directory of the file here.

Output: {filename: 'index.js', // output filename path: path.resolve(__dirname,'./build') // Specify the generated directory}Copy the code

Packaging HTML files

1. Create a file

Next, we started to package the HTML file. First, we created a pages folder under the SRC folder, and then added an index.html file inside it, and put a little code inside.

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, > <title>Document</title> </head> <body> <h1>Welcome to Webpack!! </h1> </body> </html>Copy the code

2, configuration,

Additional plug-ins need to be downloaded when the HTML file is packaged

npm install html-webpack-plugin --save-dev

After the download is successful, we can configure webpack.config.js, first introduce the plug-in we just downloaded, and then add a plugins under module.export, which is used to configure the needed plug-in. After the configuration, we execute the packaging command, and the packaged HTML file is added in the generated dist folder.

const path = require('path') // Call the path
const HtmlWebpackPlugin = require('html-webpack-plugin')  // Introduce a plug-in that packs HTML

module.exports = {
  mode: 'development'.// Development mode
  entry: './src/index.js'.// Import file
  output: {
    filename: 'index.js'.// Output the file name
    path:path.resolve(__dirname,'./dist') // Specify the directory for the generated files
  },
  / / the plugin
  plugins: [
    // html 
    new HtmlWebpackPlugin({
      template:  path.resolve(__dirname, './src/pages/index.html'), // File template
      filename:'index.html'.// Output the file name]}}),Copy the code

Packing results:

And you can see the packed one hereindex.htmlIs automatically introduced inindex.jsFile.

Packing CSS files

1. Create a file

We started packing the CSS file, first create a new CSS folder under the SRC folder, then create a new index.css file inside, put some styles inside, here we add a color to the H1 tag.

Then we’ll go to the index.js file and import the CSS file

2. Download the plug-in and configure it

NPM install –save-dev style-loader css-loader For some information about loader, please refer to the official documentation. After downloading the plugin, we can continue to configure webpack.config.js. In the previous example, we added a plugins to module.export to package the HTML. In this case, we need to add modules to configure the rules. There are many different configurations of rules on the web, and they are written differently.

const path = require('path') // Call the path
const HtmlWebpackPlugin = require('html-webpack-plugin')  // Introduce a plug-in that packs HTML

module.exports = {
  mode: 'development'.// Development mode
  entry: './src/index.js'.// Import file
  output: {
    filename: 'index.js'.// Output the file name
    path:path.resolve(__dirname,'./dist') // Specify the directory for the generated files
  },
  module: {
    rules: [{test:/\.css$/./ / CSS configuration
        use: [ 'style-loader'.'css-loader' ]  / / note}},/ / the plugin
  plugins: [
    // html 
    new HtmlWebpackPlugin({
      template:  path.resolve(__dirname, './src/pages/index.html'), // File template
      filename:'index.html'.// Output the file name]}}),Copy the code

Use style-loader before CSS -loader; otherwise error will be reported.

After the configuration, execute the package command, and then open the index.html in the dist folder. You can see that the color of the text on the page has changed.

3. Package less files

The difference between less packaging and CSS is that you need to download an extra loader to parse less. NPM install less less-loader –save-dev. Add an h2 to index. HTML, create an index.less under the CSS folder, put a little style in it, and add the index.js folder to index.js.

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, > <title>Document</title> </head> <body> <h1>Welcome to Webpack!! </h1> <h2>Welcome to Webpack!!! </h2> </body> </html>Copy the code

Continue to configure config.js. As with the CSS configuration above, the order of use should be fixed.

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

Execute the package command and open index.html in the dist folder. You can see that the style of the page content has changed.

Complete configuration file

1, package. Json

{
  "name": "webpack_project"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
    "build": "webpack"
  },
  "keywords": []."author": ""."license": "ISC"."devDependencies": {
    "css-loader": "^ 6.2.0"."html-webpack-plugin": "^ 5.3.2." "."less": "^ 4.4.1"."less-loader": "^ 10.0.1." "."style-loader": "^ 3.2.1." "."webpack": "^ 5.52.1"."webpack-cli": "^ 4.8.0"}}Copy the code

2, webpack. Config. Js

const path = require('path') // Call the path
const HtmlWebpackPlugin = require('html-webpack-plugin')  // Introduce a plug-in that packs HTML

module.exports = {
  mode: 'development'.// Development mode
  entry: './src/index.js'.// Import file
  output: {
    filename: 'index.js'.// Output the file name
    path:path.resolve(__dirname,'./dist') // Specify the directory for the generated files
  },
  module: {
    rules: [{test:/\.css$/,
        use: [ 'style-loader'.'css-loader' ]  // This must be the order
      },
      {
        test: /\.less$/,
        use: [{
            loader: "style-loader" 
        }, {
            loader: "css-loader" 
        }, {
            loader: "less-loader"}}}]],/ / the plugin
  plugins: [
    // html 
    new HtmlWebpackPlugin({
      template:  path.resolve(__dirname, './src/pages/index.html'), // File template
      filename:'index.html'.// Output the file name]}}),Copy the code

conclusion

This section introduces a simple package of JS, HTML, and CSS. Later, it will explain how to package multiple files separately, such as js, CSS subpackage, how to clean cache, file migration, and the use of some plug-ins.

This is the first time for the author to write a technical article, and I will update it gradually in the following. if there are any mistakes in the article, I hope you can point them out and give me more support!!

Three grams of oil!!