preface

First of all, we first understand what front-end engineering is, and then look at the solutions of front-end engineering solutions, and then understand the basic use of WebPack and its commonly used plug-ins. Finally, take a look at how WebPack implements packaged distribution and how Source Map can help us troubleshoot.


Front-end engineering

Front end vs. actual front end development

  1. The front of the eye

As long as you know HTML, CSS, JavaScript, you can develop a quick layout structure. LayUI is like you want to manipulate the DOM or send an Ajax request to the server

  1. Actual front-end development

Modularization (modularization of JS, CSS and resources) modularization (reuse of existing UI structure, style and behavior) standardization (division of directory structure, standardization of coding, standardization of interface, standardization of documents, Git branch management) automation (automatic construction, automatic deployment, automatic testing)

What is front-end engineering

In the enterprise front-end project development, the front-end development required tools, technology, process, experience, standardization.

Three, front-end engineering benefits

Front – end development system, a set of standard development programs and processes.

Fourth, front-end engineering solutions

  1. Early front-end engineering solutions

grunt(https://www.gruntjs.net/) gulp(https://www.gulpjs.com.cn/) 2. The front end of the current mainstream engineering solution webpack parcel (https://www.webpackjs.com/) (https://zh.parceljs.org/)

webpack

What is Webpack

1, concept,

Specific solutions of front-end project engineering

2. Main functions

Can provide friendly front-end modular development support, as well as code compression confusion, handling browser side JavaScript compatibility, performance optimization and other powerful functions

3, good

Let programmers focus on the implementation of specific functions, improve front-end development efficiency and project maintainability. ,

2. Basic use of Webpack

1. Install WebPack in your project

NPM install [email protected] [email protected] -d

2. Configure WebPack in your project

Create a new webpack.config.js file in the root directory of the file and write the following code in the file

module.exports = {
    // Specify the build mode with two optional parameters
    // Use development in the development phase because it is fast to package
    // Production is used in the launch phase, because the project launch requires a small file size
    mode:'development'
}
Copy the code
  1. This parameter is optional for the mode object
  • development

The development environment does not perform code compression and performance optimization on the files generated by packaging. The packaging speed is fast and suitable for use in the development stage

  • production

The production environment performs code compression and performance optimization on the files generated by packaging. The packaging speed is slow and is only suitable for project release

  1. What the webpack.config.js file does

Webpack.config.js is the webpack configuration file. Webpack reads this configuration file to package the project based on the given configuration before actually starting to package the build. Note: Webpack is a packaging tool developed based on Node.js, so in its configuration file, support to use node.js-related syntax and modules for webpack personalized configuration.

In the scripts node of package.json, add the following dev script

"scripts": {// npm run dev
    "dev":"webpack"
}
Copy the code

Run NPM run dev in CMD terminal to start webPack for the project package build

3, Webpack packaging entrance and exit

  1. The default conventions

In webpack 4.x and 5.x, there is a default convention ① the default package entry file is SRC -> index.js ② the default output file path is dist -> main.js 2. Customizing the entry and exit of packaging In the webpack.config.js configuration file, the entry node specifies the entry of packaging. Specify the packaged exit through the output node

const path = require('path')

module.exports = {
    mode:'development'.//entry:' Specify which file to process '
    entry:path.join(__dirname,'src/xxx.js'),
    // Specify where to store the generated files
    output: {// The directory to store
        path: path.join(__dirname,'dist'),
        // The generated file name
        filename: 'bundle.js'}}Copy the code
  1. Problem: Every time you modify the source code, you need to do it in the terminalnpm run dev Command. Very troublesome!

Plug-ins in WebPack

1. The webPack plugin

By installing and configuring third-party plug-ins, you can extend the power of WebPack and make it easier to use.

2. Common plug-ins

  1. webpack-dev-server
  • role

Similar to the Nodemon tools used in the Node.js phase, webPack will automatically package and build the project whenever the source code is modified

  • NPM command

Run the following command: NPM install [email protected] -d

  • configuration

Modify package.json -> scripts dev command as follows: run the NPM run dev command again to package the project again. Visit http://localhost:8080 in the browser to view the package effect

"scripts": {
   "dev":"webpack serve"
}
Copy the code

Note: The generated export file is in the root directory and is saved in memory

  1. html-webpack-plugin
  • role

The HTML plug-in in WebPack allows you to customize the content of the index.html page

  • NPM command

Run the following command: NPM install [email protected] -d

  • configuration

Configure it in the webpack.config.js file

// Import the html-webpack-plugin plugin to get the constructor of the plugin
const HtmlPlugin = require('html-webpack-plugin')

// Create an instance object of the HTML plug-in
const htmlPlugin = new HtmlPlugin({
    // Specify a path for storing the original file
    template:'./src/index.html'.// Specify the path to the generated file
    filename:'./index.html'
})

module.exports = {
    mode:'development'.// htmlPlugin takes effect via plugins
    // An array of plugins that webPack will load and call when it runs in the future
    plugins:[htmlPlugin]
}
Copy the code

Note: a script is automatically injected into index.html and the copied index.html page is also stored in memory

3. DevServer node

Add the following to webpack.config.js

devServer : {
    // Automatically open the browser after the initial packaging
    open:true.// Change the port number
    // In HTTP, the port number 80 can be omitted
    port:80.// Specify the address of the running host
    host:'127.0.0.1'
}
Copy the code

Note: if you modify the webpack.config.js configuration file, or modify the package.json configuration file, you must restart the real-time packaging server, otherwise the latest configuration file will not take effect!

Webpack loader

In actual development, WebPack can only package modules with.js extensions by default. Webpack cannot process other modules whose names do not end with.js suffix by default. You need to call loader to pack them normally, otherwise an error will be reported.

1. The function of loader

Assists WebPack in packaging specific file modules.

2. Common loader

  • Packing and processing CSS files (CSS-loader)
  • NPM command

Run NPM I [email protected] [email protected] -d

  • configuration

In the module -> rules array of webpack.config.js, add the loader rule as follows

module: {rules: [//test is the file type
        //use Indicates the loader to be invoked
        {test:/\.css$/,use:['style-loader'.'css-loader']]}}Copy the code

Note: The loader sequence in use is fixed, and the call sequence is called from back to front.

  • Packing and processing less files (less-loader)
  • NPM command

Run the NPM I [email protected] [email protected] -d command

  • configuration

In the module -> rules array of webpack.config.js, add the loader rule as follows

module: {rules: [// Match rules for file name extensions
        {test:/\.less$/,use:['style-loader'.'css-loader'.'less-loader']]}}Copy the code
  • Package files related to the URL path in the processing stylesheet (file-loader)
  • NPM command

Run NPM I [email protected] [email protected] -d

  • configuration

In the module -> rules array of webpack.config.js, add the loader rule as follows

module: {rules: [// Loader to process image files
        // If only one loader needs to be called, then the value passes a string, such as multiple loaders
        {test:/\.jpg|png|gif$/,use:'url-loader? limit-22229'}}]Copy the code

Among them? The loader argument follows:

Limit specifies the size of an image in bytes. Only images whose size is less than or equal to limit are converted to Base64Copy the code
  • Advanced syntax in package processing JS files (babel-loader)
  • NPM command

Run NPM I [email protected] @babel/[email protected] @babel/[email protected] -d

  • configuration

In the module -> rules array of webpack.config.js, add the loader rule as follows

module: {rules: [// To configure babel-loader, the programmer only needs to convert his own code; Be sure to exclude js files in the node_modules directory
        {test:/\.js$/,use:'babel-loader'.exclude:/node_modules/}}]Copy the code

Create babel.config.js in the root directory and define the following configuration items for Babel:

module.exports = {
    // Declare the plugins available for Babel
    plugins: [['@babel/plugin-proposal-decorators', {legacy:true}}]]Copy the code

Packaging releases

First, why package release?

  • In the development environment, the generated files are stored in the memory and cannot be obtained
  • In the development environment, the generated files are not compressed or optimized for performance

Configure webpack distribution

Under the scripts node of package.json file, add the following build command:

"scripts": {In the development environment, run the dev command
    "dev":"webpack serve".// Run the build command when the project is published
    "build":"webpack --mode production"
}
Copy the code

— Model is a parameter that specifies the mode in which WebPack will run. Production represents the production environment and performs code compression and performance optimization on the files generated by packaging.

Note: The parameter specified by –model overrides the model option in webpack.config.js

1. Generate JavaScript files into the JS directory

In the output node of the webpack.config.js configuration file, do the following:

output: {
	path: path.join(__dirname,'dist'),
	// Explicitly tell WebPack to put the generated bundle.js file in the JS subdirectory in the dist directory
	filename: 'js/bundle.js'
}
Copy the code

2. Uniformly generate the image files into the image directory

Modify the url-loader configuration item in webpack.config.js and add the outputPath option to specify the outputPath of the image file:

{
	test: /\.jpg|png|gif$/,
	use: {
		loader: 'url-loader'.options: {
			limit: 22228.// Explicitly specify that the image files generated by packaging are stored in the image folder in the dist directory
			outputPath: 'image'}}}Copy the code

3. Automatically clean old files in dist directory

Refer to the website: https://www.npmjs.com/package/clean-webpack-plugin

Source Map

What is Source Map?

It’s an information file that stores the location information. In other words, the Source Map file stores the position of the compressed and obfuscated code before the transformation.

Two, how to use?

  1. In the development environment

It is recommended to add the following configuration to webpack.config.js to ensure that the number of error lines is consistent with the number of lines in the source code

module.exports = {
    mode:'development'.devtool:'eval-source-map'
}
Copy the code
  1. Production environment

If the devtool option is omitted, the resulting file does not contain the Source Map. This prevents the original code from being exposed to someone else in the form of a Source Map. Or setting devtool to nosource-source-map will only locate the number of lines in error and not expose the source code.

supplement

NPM command supplement

  1. – S is--saveThe shorthand

-d = “save-dev”; -d = “devDependencies”; -d = “devDependencies” Place the file in devDependencies

Use @ to indicate the SRC source directory

Add a resolve node to webpack.config.js

resolve:{
    alias: {// Tell Webpack that the @ symbol represents the SRC directory in the programmer's code
        The '@':path.join(__dirname,'/src/')}}Copy the code

conclusion

For a front-end engineering solution, Vue provides us with the Vue CLI scaffolding tool, which is built on WebPack and comes with reasonable default configuration. It allows us to focus on writing apps instead of spending days obsessing over configuration issues. Finally to everyone in the Vue CLI website address https://cli.vuejs.org/zh/, call it a day here, bye ~