[webpack] Introduction - use webpack for engineering development

Keywords: Webpack

Using webpack for engineering development

1. Check the locally installed version

webpack -v

2. Install locally and globally (specify version)

// Install core library
npm install webpack@4 -g
// Installation tools
npm install webpack-cli@3 -g

3. Install webpack in the current project

  • Initializes a package description file in the current project
npm init -y
  • Then install webpck and webpack cli (development environment-D)
npm install webpack@4 -D
npm install webpack-cli@3 -D

Packaging files using webpack

1. Create the src directory, create main.js in the src directory, and prepare some JS files

  • demo1.js
// Create an add method and export it
let add = function(x, y) {
  return x+y
}

export default {
  add
}
  • demo2.js
// add method of introducing demo1 module
import { add } from './demo1'

const [num1, num2] = [100, 20]
const res = add(num1, num2)
console.log('Calculation results:', res);
  • main.js
// main.js is our entry file

// All files to be executed should be imported in the entry file
import './demo2'

2. Create a new webpack.config.js

  • The configuration is written in module.exports

  • There are five configuration items: entry, output, loader, plugin and configuration

  • Write the following code:

const path = require('path')

module.esports = {
    // 1. Entrance
    entry: './src/main.js', // Specify entry file
    // 2. Output
    output: {
        filename: 'app.js', // Name of the output file
        path: path.resolve(__dirname, 'dist') // Output directory__ dirname is the project address and dist is the package directory
    }
    // 3.loader
    // 4.plugin
    // 5.configuration
    mode: 'development' // Packaging mode, optional production and development
}
  • Execute the command webpack on the console

  • Executing a command directly using the editor may report the following error: webpack: the file D:\node-v14.17.0-win-x64\webpack.ps1 cannot be loaded because running scripts is prohibited on this system. Letter for details
    For information, see about in https:/go.microsoft.com/fwlink/?LinkID=135170_ Execution_ Policies.
    Location line: 1 character: 1

    Solution: run PowerShell as an administrator, and then execute the command set executionpolicy remotesigned. Select Y as the pop-up option.

  • After the successful execution of webpack, you can see that a dist directory is generated in the directory, and there is an app.js file below.

  • mode uses development to package and generate larger files, while production generates smaller files.

Automatic generation of html files using webpack

  • We have packaged the JS of each module in the project into app.js, but if we want to use this JS, we have to manually write an html file and reference app.js.
  • Next, we use the plugin (plug-in) to let webpack automatically help us generate html and automatically introduce the packaged js file.

1. Install the plug-in HTML webpack plugin

npm install html-webpack-plugin@3.2.0 -D

2. Introduce plug-ins in webpack.config.js

  • First, introduce the plug-in before module.exports
const HtmlWebpackPlugin = require('html-webpack-plugin')
  • Add the configuration item plugins in module.exports. Plugins is an array, indicating that many plug-ins can be referenced.
plugins: [
	new HtmlWebpackPlugin()
]
  • When you execute the webpack command, you can see that an html file is generated in the dist directory, as follows
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Webpack App</title>
  </head>
  <body>
  <script type="text/javascript" src="app.js"></script></body>
</html>
  • Preview this html in the browser, and you can see the calculation result on the console: 120, which is the result of the add method we wrote in demo1 and then called and executed in demo2.

3. Specify html template

  • You can specify an html template and let webpack generate html according to the specified template.
  • Create a public directory in the project, create index.html below, and add the following content
<!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, initial-scale=1.0">
  <title>My WebPage</title>
</head>
<body>
  <h1>This is what I designated html Template</h1>
</body>
</html>
  • Modify plugins configuration item
plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html'
    })
  ],
  • When you execute webpack, you can see that the generated html is a packaged js file based on the template.
<!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, initial-scale=1.0">
  <title>My WebPage</title>
</head>
<body>
  <h1>This is what I designated html Template</h1>
<script type="text/javascript" src="app.js"></script></body>
</html>

Packaging css files using webpack

  • The effect of the above implementation is only js and html, lacking style. However, webpack can only package js and json files by default.
  • Create static - > CSS - > index.css in src directory and add any style
body {
  background-color: lightslategray;
}
  • When webpacpk is executed, it is found that there is no loader: error in. / SRC / static / CSS / index.css 1:5
    Module parse failed: Unexpected token (1:5)
    You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

  • If you want to realize the ability of packaging css, you have to use loader, which can be understood as a translator.

  • First install CSS loader and style loader

npm install css-loader@5.2.0 style-loader@2.0.0 -D
  • Compared with plugin, loader is simpler and can be used directly without introduction
  • The configuration loder should be written in the module. Rules is an array. The reading and parsing rules of the configuration module are usually used to configure the loader.
module: {
    rules: [
      {
        test: /\.css$/i, // Matching file, css file
        use: ['style-loader', 'css-loader'] // The loader is loaded from right to left, so you should write CSS loader after it (read it first)
      }
    ]
  },
  • Execute the webpack again, and preview the html in the browser. You can see that the style takes effect and the page has a blue background.

Posted by PhotoClickr on Sat, 18 Sep 2021 21:25:45 -0700