First, front-end development

  • Modularization: JS modularization, CSS modularization, resource modularization
  • Componentization: Reuse UI structural styles
  • Standardization: directory structure division, code standardization, interface standardization, document standardization, Git branch management
  • Automation: Automated build, automated deployment, automated testing

1. Front-end engineering

In the enterprise front-end project, the front-end development required tools, technology, process, experience and other standardized, standardized.

2. Front-end engineering solutions

Webpack and parcel

2. Webpack

Engineering collective solutions for front-end projects. Main features: support front-end modular development, code compression and confusion, dealing with browser side JavaScript compatibility, performance optimization.

In Webpack, everything is modular and can be imported and used using es6 import syntax (jquery, CSS, less files, images). (CSS, LESS, etc.)

1. Basic use

Interlaced discoloration cases:

  1. Create a blank directory for the project and run NPM init -y to initialize the package.json configuration file
  2. Create a new SRC source directory
  3. Create index.html and index.js files in the SRC directory
  4. Initialize the basic structure of the index. HTML home page
  5. Run NPM install jquery -s to install jquery
  6. Import jQuery in ES6 modular mode to achieve interlaced color change effect

2. Install WebPack in the project

NPM install [email protected] [email protected] -d (-d is short for --save-dev)Copy the code

3. Configure WebPack in the project

1. Webpack.config.js (webpack configuration file)

Module. export={mode:'development' //mode refers to build mode, development or production}Copy the code

Webpack reads this configuration file to package the project based on the given configuration before actually starting to package the build. Webpack is a packaging tool developed based on Node.js, so its configuration file supports personalized configuration of Webpack using Node.js-related syntax and modules. The mode node has two optional values:

  • development

The development environment will not compress the code and optimize the performance of the files generated by packaging. The large volume is fast and suitable for use in the development stage

  • production

The production environment will compress the code and optimize the performance of the files generated by packaging. The packaging speed is very slow and is only suitable for the project release phase

Development was used in the development stage (fast packaging but large volume), and Production was used in the release stage (code compression and confusion would occur when packaging, small release size but slow packaging).

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

"Scripts ": {"dev":"webpack" // scripts under script can be executed by NPM run, such as NPM run dev (execute webpack command)},Copy the code

3. Run the NPM run dev command in the terminal to start webpack for project packaging and construction. When running the command, read the webpack.config.js configuration file first, and run webpack according to the configuration file for development or production.

Emitted by Webpack asset main.js 88.3 KiB [Notifying Note] [Notifying Note] (name, note: main) runtime modules 663 bytes 3 modules cacheable modules 282 KiB ./src/index.js 563 bytes [built] [code generated] ./node_modules/jquery/dist/jquery.js 282 KiB [built] [code generated]Copy the code

After the execution, with directory will appear in the dist folder,. / SRC/index. Js and. / node_modules/jquery/dist/jquery js code in the packaging in the main. Js file. The main.js file should be included in the script tag in the index.html package.

The default packing entry file is SRC -> index.js, and the default output file is dist -> main.js. The default convention for packaging can be modified in webpack.config.js

4. Customize the entry and exit of the webpack.config.js configuration file and specify the entry of the package through the entry node. Specify the packaged exit through the output node.

Module.export ={const path=require('path') // Use node.js export syntax to export a webpack configuration object module.export={// represent webpack run mode, Optional values are Development and production mode:'production', // entry:' Specify which file to process 'Entry: path2d. join(__dirname,'./ SRC /index1.js'), Output :{// To the directory path:path.join(__dirname,'dist'), // to generate the file filename:'bundle.js'}}Copy the code

After using Webpack, the effect can not be refreshed directly in the webpage for each code modification. Instead, you need to run webpack (update dist folder) again in the terminal to refresh the effect.

3. Webpack plug-in

1.webpack-dev-server

Real-time automatic packaging, monitoring the change of project source code, modified code will be recognized after saving automatic packaging.

Install webpack dev – server:

NPM install [email protected]Copy the code

Configuration webpack dev – server:

Modify the dev command in scripts in package.json

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

Run the NPM run dev command again to package the project again. Visit http://localhost:8080 in the browser to view the automatic package effect. The package file will be saved to the memory. Enter the file directory and click SRC to enter the index home page.

Note: Webpack-dev-server starts a live packaged HTTP server

2.html-webpack-plugin

Html-webpack-plugin is an HTML plug-in in Webpack that allows you to customize the contents of an index. HTML page.

Use the html-webpack-plugin to copy the index.html home page from the SRC directory into the project root directory

Install the HTML-webpack-plugin

NPM install [email protected] - DCopy the code

Configure the HTmL-webpack-plugin plugin

webpack.config.js

Const HtmlPlugin=require('html-webpack-plugin') //new constructor, Const htmlPlugin =new htmlPlugin ({template:'./ SRC /index.html', filename:'./index.html' }) module.exports = { mode: Plugins :[htmlPlugin], // Through the plugin node, make htmlPlugin plugin effect};Copy the code

The index.html page, copied to the project root directory via the HTML plug-in, is also put into memory. The HTML plugin automatically injects the bundle.js file into the generated index.html page, eliminating the need to manually import the bundle.js file into the index.html page.

3. DevServer node

The webpack.config.js configuration file, configured through the devServer node

DevServer: {// Open :true, // in HTTP protocol, if the port number is 80, you can omit (localhost) port:80; Host :'127.0.0.1'}Copy the code

4. Webpack loader

1. Summary of loader

In actual development, WebPack can only package modules with.js extensions by default.

Other modules that do not end with.js suffix cannot be processed by webpack by default. You need to call loader to pack normally, otherwise an error will be reported.

Loader helps WebPack process specific file modules. Css-loader can be packaged CSS related files less-loader can be packaged CSS related files babel-loader can be packaged to handle advanced JS syntax that webPack cannot handle

Loader call procedure

2. Parse and process the CSS file

Installation:

NPM I [email protected] [email protected]Copy the code

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

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

Test indicates the matched file type, and use indicates the loader to be invoked. Note: The sequence of loaders specified in the use array is fixed. Multiple Loaders are invoked from the back to the front

1. By default, webpack can only process files ending in JS, not files with other suffixes 2. Webpack can’t handle 3 by default because the code contains the index.css file. When webpack fails to process the file, webpack.config.js will be searched to check whether the rules array in module is configured with the corresponding loader. 4. 6. After the style-loader is finished, it is forwarded to the previous loader. If there is no loader, the result of the style-loader is forwarded to the previous loader. Webpack combines the style-loader results into /dist/bundle.js and wins the package

3. Parse and process less files

Installation:

NPM I [email protected] [email protected]Copy the code

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

Module :{// Match rules for all third-party file modulesCopy the code

Rules :[// Defines loaders for different modules

        {test:/.less$/,use:[‘style-loader’,’css-loader’,’less-loader’]}       ]     }

4. Package the files related to the URL path in the processing style

[Bug Mc-10868] – error importing image from base64 string js (not js file)

Installation:

NPM I [email protected] [email protected] -dCopy the code

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

The module: {rules: [/ / when there is only one loader, use the back can not use arrays, write directly to the string {test: / \. JPG | PNG | gifs $/, use: 'url - loader? Limit = 22229'}]}Copy the code

Among them? Limit specifies the size of the image in bytes. Only the image whose size is less than or equal to limit is converted to base64

5. Package advanced syntax in js files

Webpack can only be packaged to handle a portion of advanced JavaScript syntax. For those advanced JS syntax that WebPack can’t handle, use babel-Loader for packaging.

Install babel-loader package:

NPM I [email protected] @ Babel/[email protected] @ Babel/[email protected]Copy the code

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

Module :{// Match rules for all third-party file modules

Rules :[// defines loader for different modules // When configuring babel-loader, programmers only need to convert their own code, and must exclude JS files in node_modules. Js compatibility in third-party packages is not needed by programmers

{test:/.js$/,use:’babel-loader’,exclude: /node_modules/}]} Configure babel-loader: In the root directory of the project, create a configuration file named babel.config.js and define the configuration items of Babel as follows:

Module.exports ={// declare available plug-ins // in the future when webpack calls babel-loader, Plugins :[['@babel/plugin-proposal-decorators',{legacy:true}]]}Copy the code

Five. Package

1. Why is it packaged

After the completion of project development, webpack is needed to package and publish the project, mainly for the following two reasons: ① In the development environment, the generated files are stored in memory, and the final generated files cannot be obtained. ② In the development environment, the generated files are not compressed and optimized for performance. In order to enable the project to run in the production environment with high performance, the project needs to be packaged and released.

2. Configure the webPack publishing function

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

"scripts": { "dev": "Webpack serve",// in the development environment, run dev command (build file in memory) "build":"webpack --mode production" // when the project is published, run build command (build file on physical disk (dist folder)},Copy the code

–mode is a parameter that specifies the running mode of webPack. Production represents the production environment and performs code compression and performance optimization on the files generated by packaging. Note: The –mode parameter overrides the mode option in webpack.config.js.

The NPM run build command is used for packaging and publishing

3. Generate JavaScript files into the JS directory

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

output:{
Copy the code

Join (__dirname,’dist’), // explicitly tells Webpack to store the bundle.js file in the js subdirectory of dist. Filename :’js/bundle.js’}

4. Generate the image files in 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:

Module :{rules:[// If there is only one loader, use can be written as a string instead of an array. // When configuring urL-loader, separate multiple parameters with &. OutputPath installed package directory of images with {test: / \. JPG | PNG | gifs $/, use: 'url - loader? Limit = 22229 & outputPath = images'}]}Copy the code

5. Automatically delete old files in the dist directory

The clean – webpack – plugins plugin

Installation:

npm install --save-dev clean-webpack-plugin

Configuration: webpack. Config. Js

// Import the plug-in as needed, and after obtaining the constructor of the plug-in, Const {CleanWebpackPlugin}=require('clea-webpack-plugin') const claenPlugin=new CleanWebpackPlugin() Mount the created cleanPlugin instance object into the Plugin node. Plugins :[htmlPlugin,cleanPlugin],// Mount pluginsCopy the code

Six. Source Map

Problems encountered in production environment:

Before the front-end project is put into production environment, the JavaScript source code needs to be compressed and confused, so as to reduce the size of files and improve the loading efficiency of files. This inevitably leads to another problem: debugging code after compression obfuscation is extremely difficult. Whitespace and comments are removed; Variables are replaced with names without any semantics.

A Source Map is an information file that stores location information. In other words, the Source Map file stores the position of the compressed and obfuscated code before the transformation. With it, when an error occurs, the debugging tool will directly display the original code, rather than the converted code, which can greatly facilitate later debugging.

In the development environment, WebPack has Source Map enabled by default. When a program fails to run, you can directly display the error line on the console and locate the specific source code.

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 = {// Devtool :'eval-source-map', // devtool:'eval-source-map', // devtool:'eval-source-map' Devtool :' nosource-source-map '// display the source code of the error line. Devtool :'source-map'}Copy the code

In a 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;

If you just want to locate the exact number of lines in the error, and you don’t want to expose the source code. In this case, you can set devtool to nosource-source-map.

If you want to locate the error line number at the same time, show the specific error source. You can set the devtool value to source-map.

With this option: you should configure your server to not allow ordinary users to access the Source map file!

7. @ webpack

Use @ to represent the SRC source directory

Configuration:

webpack.config.js

Resolve: {alisa describes: {/ / tell webpack, @ on behalf of the SRC directory '@' : path. Join (__dirname, '. / SRC/')}Copy the code