This is the eighth day of my participation in Gwen Challenge

Unified modular specification -ES6 modular

1. Experience ES6 modularity through Babel in Node. js

  1. Open the terminal and enter the following command:
npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node
Copy the code
  1. Once installed, type install:
npm install --save @babel/polyfill
Copy the code
  1. Project root directory is createdbabel.config.jsFile, internal code as follows
const presets = [
    ["@babel/env", {targets: {edge:"17".firefox:"60".chrome:"67".safari:"11.1"}}]]/ / exposure
module.exports = { presets }
Copy the code
  1. Create a test file (just print something)
// create index.js file
console.log('ok');
Copy the code
  1. Run commands on the terminal
npx babel-node ./index.js
Copy the code

2.ES6 modular basic syntax

Set up default imports and exports

Default export syntax:

export default{member A, member B... }Copy the code

Method of use

let num = 10;
let cnt = 2;
export default {
    num
}// Only num is exposed
Copy the code

Default import syntax

Note: The receive name is self-defined, the name used in the current file

// import receive name from "module identifier"
import index from './index.js'
console.log(index);// { num: 10 }
Copy the code

Note: In a module, export default can be used only once to expose members. Do not write more than one export default, otherwise an error will be reported

Small tip:

  1. If no member is exposed in a module, other modules importing the module will get an empty object
  2. Unexported values can be read from an exported function
/ / index. Js file
let num = 10;
let cnt = 2;
function showCnt() {
    console.log(cnt);
}
export default {
    num,
    showCnt,
}// The CNT is not exported

/ / m1. Js file
import index from './index.js'
index.showCnt();/ / 2
Copy the code
Import and export as required

Export syntax as needed

export let age = 998;
export let name = 'ljc'
Copy the code

Import syntax on demand

import {age, name} from './m2.js'
console.log(name + age);// ljc19
Copy the code

The export name must correspond to the attribute name. You can use as to set the alias, for example:

import {age ,name as nickname} from './m2.js'
console.log(nickname + age);//ljc19
Copy the code

This accomplishes setting the alias, and the original name cannot be used after setting the alias

Both default and on-demand methods coexist

// export the m2.js file
export let age = 19;
export let name = 'ljc'
let sex = 'male'
export default {
    sex
}
// import m1.js file
import m2, {age, name as nickname} from './m2.js'
console.log(m2);// {sex: 'male'}
console.log(nickname + age); //ljc19
Copy the code

Note: A module can import and export on demand or by default

Import and execute the code directly
 import "./m2.js";
Copy the code

Execute directly without receiving exposed members in the module

Webpack body

Webpack provides modularization support, code compression confusion, js compatibility solution, performance optimization and other features, improving development efficiency and project maintainability

It is more meaningful to learn from actual combat. I watched a lot of lecturers’ videos before, which was a bit boring and unreasonable. I have no idea what I have learned after listening to them

Create list interlaced color changing items

  1. Create and initialize the project directory

The terminal runs the NPM init -y command to initialize the package manager configuration file package.json

Project directory

SRC --> index.html // create index file in SRC folderCopy the code
  1. Create the home page and js file

Write the structure of the interlacing project and create the index.js file in the SRC directory

  1. The installationjQuery

Enter the command NPM install jquery -s

Note: this is jquery, not jquery

  1. The importjQuery
import $ from "jquery";
$(function(){$('li:odd').css('backgroundColor'.'pink');
    $('li:even').css('backgroundColor'.'blue')})Copy the code

At this time, an error will be reported when the project runs. The first line of code originally belongs to ES6 syntax, and the browser has compatibility problems

So we use Webpack to convert the code into browser-compatible code

Basic use of Webpack

I have learned this part for many times, so my notes have a feeling of foretelling the future. I hope I can have a good result this time

Install and configure the WebPack file
  1. Run the NPM install webpack webpack-cli -d command to install webpack-related packages

  2. Create the webpack.config.js file in the root directory and call it from the user-defined configuration file in preference when executing webpack

  3. Write the following code in the configuration file,

Note: Mode means file export format, including production mode and development mode. The code in production mode will be compressed to remove all Spaces and so on. The code file is small, but it is not conducive to our learning, so we still set it to development mode when learning

This configuration file will add a lot more content later in the study

module.exports = {
  mode:"development"// Can be set to development, production
}
Copy the code
  1. Modify thepackage.jsonFile, add a little bit of stuff
/ / not add
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",}/ / add after
"scripts": {"test": "echo \"Error: no test specified\" && exit 1"."dev": "webpack"
}
Copy the code

Configuration properties under script objects that can be run through NPM run

For example: NPM run dev, run dev to start webpack service for project packaging

If I get an error here

  1. Please check whether both index files exist insrcdirectory
  2. It could be installationjquery“In capital lettersQ

After executing the command, we will notice that there is a dist folder in the project directory. This folder contains the webpack files that are converted to browser-compatible code in our project, so we can import this file into our index. HTML file.

In layman’s terms, this is a converted file, and it does exactly what we wrote earlier, but it’s compatible, so when we refer to it, we just refer to it

Configure the webPack entry and exit

SRC /index.js is the default package entry JS file and dist/main.js is the default package output JS file

We can customize the import/export file by configuring the configuration file we created earlier (webpack.config.js)

const path = require('path');// Import the module of the operation path in Node.js
module.exports = {
    entry: path.join(__dirname,"./src/index.js"),// Set the entry file path, absolute path
    // Configure the export file
    output: {path:path.join(__dirname,"./dist"),// Set the path
        filename:"res.js"// Set the name of the exported file
    },
    // Mode selection
    mode: "development"
}
Copy the code

In the above code we refer to the path module in Node. Path.join () is used to connect paths, and will correctly use the current system path separator, which is the absolute path

Note: in the above code entry file path, according to their own file directory to write, CV probability error oh

Set up webpack automatic packaging

We had to repackage the code every time we changed it, which was too much trouble, so it had to be packaged automatically

  1. Install the automatic packaging tool
npm install webpack-dev-server -D
Copy the code
  1. Modify the package.json filedevDirective, which is the property we added ourselves earlier (version 4.x)
/ / modify before
"dev": "webpack"
/ / modified
"dev": "webpack-dev-server"
Copy the code

Note: If the webpack version is 5.x, you need to change the configuration file above to “dev”: “webpack Server “, otherwise an error will be reported. Or run it with NPX Webpack Serve

You can run the webpack -v command to view the webpack version

  1. Run NPM run dev to do the packaging
  2. In the run result, there is relevant information
I "WDS" : Project is running at http://localhost:8080/ I "WDS" : Webpack output is served from /Copy the code

The first line is the server address that we can access to run our web page

The second line is that the output path of the file is /, which means that the file is stored in the root directory of the server

Note: Output files automatically packaged by WebPack Server are placed in the server root directory by default

These address file directories, we can change through the configuration file

  1. Remember to import the JS file into the page, as you know from step 4, the file is stored in the root directory of the server, so
<script src="/bundle.js"></script>
Copy the code
  • Webpack Server starts a live packaged HTTP server
  • The output file is in the server, not visible in the project directory, which is not very friendly
Configure HTML – webpack – the plugin

Using this plugin to generate a preview page solves the problem that when we visit 8080, we will not see the page directly

  1. The installation packagehtml-webpack-plugin
npm install html-webpack-plugin -D
Copy the code
  1. Modifying a Configuration File

Import the downloaded package and configure the corresponding file

/ / import packages
const HtmlWebpackPlugin = require("html-webpack-plugin");
// Create an object
const htmlPlugin = new HtmlWebpackPlugin({
    // Set the template file to generate the preview page
    template:"./src/index.html".// Set the name of the generated preview page
    filename:"index.html"
})
Copy the code

In this object, add the plugins attribute and place the instantiated object in it

Note: Plugins have s

module.exports = {
    ...
    plugins:[ htmlPlugin ]
}
Copy the code

In many videos, I write the configuration file in general first, but not in this video, which is a little strange

Configure automatic packaging parameters

Change the dev property in the package.json file again

"dev": "webpack server --open --host 127.0.0.1 --port 9999"
Copy the code
  • --openYes Auto start
  • --hostIs the specified address
  • --portIs the specified service port number

There is also another way to do this by modifying the webpack.config.js configuration file

Add a devServer property to configure the information

module.exports = {
    ...
    output: {},devServer: {
        port: 3030.publicPath: './dist'}},Copy the code

Webpack loaders and plug-ins

By default, webPack can only package JS files. If you want to package non-JS files, you need to call the loader to do so

  • Less-loader can package files related to processing.less

  • Sass-loader can package files that handle.scss

  • Url-loader packages and processes files related to URL paths in the CSS

Loader call procedure

Note: NPM run dev is used to view the page in real time, but it does not generate a file, just a preview, so we need to use webpack when we want to generate the file

1. Package and process the CSS file
  1. Install the loader package
npm install style-loader css-loader -D
Copy the code
  1. In webpack. Config. Jsmodule -> rulesIn the array, add loader rules as follows
output: {... },module: {
    rules :[
        {
            test:/\.css$/.// If the CSS file is matched successfully, use the following loader
            use:[
                'style-loader'.'css-loader']]}},Copy the code

Note:

  • The loader order specified in the use array is fixed
  • Multiple Loaders are invoked in the following order: from back to front
  • An error may be reported if the loader placement sequence is incorrect
2. Pack and process less files
  1. Open the terminal and run the following command to download the less-loader
npm i less-loader less -D
Copy the code
  1. Add a configuration file, match the less file, and use loader to load the file
{
    test:/\.less$/,
    use:[
        'style-loader'.'css-loader'.'less-loader']}Copy the code

The rules array contains a large number of rules, each of which is an object containing test and use

3. Pack and process SCSS files

I did not succeed in this part, I checked a lot of materials, but failed. The webpack version of the video course is 4.x, I used 5.x, some things were abandoned, installation == failed ==, so I can skip this part

  1. Open the terminal, run the command, the package
npm i sass-loader node-sass -D
Copy the code
  1. To configure rules, continue adding configurations in Rules
{
    test: /\.scss$/,
    use: ['style-loader'.'css-loader'.'sass-loader']}Copy the code
4. Extract the CSS to a separate file
  1. Open the terminal and run the command
npm install --save-dev mini-css-extract-plugin
Copy the code
  1. The introduction of
// CSS is extracted into a separate file
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
Copy the code
  1. Changing user Configuration
// Change the CSS configuration
{
test: /\.css$/,
use: [
    // Change the following
    MiniCssExtractPlugin.loader,
    'css-loader']}// Create a plug-in object
plugins: [
    htmlPlugin,
    new MiniCssExtractPlugin()
]
Copy the code
5. Configure postCss to automatically add CSS compatibility codes

This is real

  1. Open the terminal and run commands to install the Loader
npm install postcss-loader autoprefixer -D
Copy the code
  1. Create and configure the postcss.config.js file in the project root directory
const autoprefixer = require("autoprefixer");/ / introduction
module.exports = {
    plugins:[ autoprefixer ]
}
Copy the code
  1. Configure rules and change the Rules array
// Change the CSS configuration
{
test: /\.css$/,
use: [
    MiniCssExtractPlugin.loader,
    'css-loader'.// Add a new Loader rule here
    'postcss-loader']}Copy the code
6. Enable CSS compression

Webpack4 uses the optimization-csS-assets-webpack-plugin plugin as above, importing and creating instance objects

The use of webpack5 is recorded below

  1. Open the terminal and install the plug-in
npm install css-minimizer-webpack-plugin --save-dev
Copy the code
  1. Introduces the creation of plug-in objects
/ / introduction
const CSSMinimizerWebpackPlugin = require('css-minimizer-webpack-plugin'); .// Create in the plugins array
plugins: [
    htmlPlugin,
    new MiniCssExtractPlugin(),
    new CSSMinimizerWebpackPlugin()
]
Copy the code
7. Pack the images in the stylesheet

In the style sheet CSS, sometimes setting the background image and setting the font file requires loader to handle the same process. Url-loader and file-loader are used to process packaged image files and font files

  1. Open the terminal and install the Loader
npm install url-loader file-loader -D
Copy the code
  1. Configuring the Loader File
{
    test:/\.(jpg|png|gif|bmp|ttf|eot|svg|woff|woff2)$/,
    use:"url-loader? limit= 8 * 1024"
}
Copy the code

Note:

  1. Files in CSS stylesheets are packaged through this plug-in
  2. ? limitIf the size is smaller than that, it will be packaged directly and stored in the path you wrote yourself. If the size is larger than that, it will be converted to base64
Pack other files

The Loader has been installed in the previous step. Add the configuration file

{
    exclude:/\.(css|js|html|less|jpg|png|gif|bmp|ttf|eot|svg|woff|woff2)$/.// Exclude these files
    loader:'file-loader'.options: {
        name: '[hash:10].[ext]'// Shorten the file name}}Copy the code
9. Package the advanced syntax of JS files
  1. Open the terminal and install Babel
npm install babel-loader @babel/core @babel/runtime -D
Copy the code
  1. Install the Babel syntax plug-in package
npm install @babel/preset-env @babel/plugin-transform-runtime @babel/plugin-proposal-class-properties -D
Copy the code
  1. Create and configure the babel.config.js file in the project root directory
module.exports = {
        presets: ["@babel/preset-env"].plugins: ["@babel/plugin-transform-runtime"."@babel/plugin-proposal-class-properties"]}Copy the code
  1. Change rules in the user profile, continue under array
{
    test:/\.js$/,
    use:"babel-loader".//use Specifies the loader to be invoked for the file type
    exclude:/node_modules/
}
Copy the code
10. Output the file to the corresponding folder

The CSS file:

Add parameter configuration at instantiation time

new MiniCssExtractPlugin({
     filename: 'css/[name].css'
})
Copy the code

Image files

Add the options configuration content in rules

{
    test: /\.(jpg|png|gif|bmp|ttf|eot|svg|woff|woff2)$/,
    use: [{
        loader: "url-loader".options: {
            limit: 8 * 1024.name: '[hash:10].[ext]'.esModule: false.outputPath: './imgs'.publicPath: './imgs' // Development environment configuration}}}]Copy the code
11. Compress HTML code

Add the plug-in configuration as above

In fact, it is configured to remove Spaces and comments

//
const htmlPlugin = new HtmlWebpackPlugin({
    // Set the template file to generate the preview page
    template: "./src/index.html".// Set the name of the generated preview page
    filename: "index.html".// Add compression code
    collapseWhitespace: true.removeComments: true.options: {
        esModule: false}})Copy the code

Complete configuration

const path = require('path'); // Import the module of the operation path in Node.js
// Import the HTML package
const HtmlWebpackPlugin = require("html-webpack-plugin");
// Create an object
const htmlPlugin = new HtmlWebpackPlugin({
    // Set the template file to generate the preview page
    template: "./src/index.html".// Set the name of the generated preview page
    filename: "index.html".// Compress the code
    // collapseWhitespace:true,
    // removeComments:true,
    options: {
        esModule: false}})// CSS is extracted into a separate file
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
/ / CSS compression
const CSSMinimizerWebpackPlugin = require('css-minimizer-webpack-plugin');
module.exports = {
    entry: path.join(__dirname, "./src/js/index.js"), // Set the entry file path
    // Configure the export file
    output: {
        path: path.join(__dirname, "./dist"), // Set the path
        filename: "js/bundle.js" // Set the export file name
    },
    module: {
        rules: [{
            / / deal with CSS
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader'.'postcss-loader'] {},/ / deal with less
                test: /\.less$/,
                use: [
                    'style-loader'.'css-loader'.'less-loader'] {},// Handle SCSS
                test: /\.scss$/,
                use: ['style-loader'.'css-loader'.'sass-loader'] {},// Process the image
                test: /\.(jpg|png|gif|bmp|ttf|eot|svg|woff|woff2)$/,
                use: [{
                    loader: "url-loader".options: {
                        limit: 8 * 1024.name: '[hash:10].[ext]'.esModule: false.outputPath: './imgs'.publicPath: '.. /imgs' // Public path}}}, {// Process other resources
                exclude: /\.(css|js|html|less|jpg|png|gif|bmp|ttf|eot|svg|woff|woff2)$/,
                loader: 'file-loader'.options: {
                    name: '[hash:10].[ext]'.outputPath: 'media'.publicPath: '.. /media' // Develop configuration or just do it}}, {// Convert high-level JS code
                test: /\.js$/,
                use: "babel-loader".exclude: /node_modules/}},devServer: {
        // Server configuration
        port: 9999.open: true
    },
    target: 'web'.// Refresh in real time
    devtool: "eval-source-map".// will be written later
    plugins: [
        htmlPlugin,
        new MiniCssExtractPlugin({
            filename: 'css/[name].css'
        }),
        new CSSMinimizerWebpackPlugin()
    ],
    // Mode selection
    mode: "development"
}
Copy the code

Performance optimized configuration

Optimize package build speed with HMR

HMR has different configurations for HTML, CSS, and JS. Js and HTML files do not use HMR by default

Problem: If we only modify the style file, unmodified js files will be reloaded for the page refresh, and all the code will be executed again. This is not always the desired effect

Solution: Use the HMR functionality to fulfill this requirement. Its function is that when a module changes, it will only repackage this module, instead of packing and loading all modules, greatly improving the build speed

devServer: {
  port: 9999.open: true.// Enable HMR
  // For the new configuration to take effect, the Webpack service must be restarted
  // re-execute the NPX webpack Server directive
  hot: true
}
Copy the code
  • After the HMR function is enabled, when we modify the style file, we can find on the console that only the style file is reloaded and refreshed, the other files will not be re-exported.

Note:

  1. There is no need to do HMR for HTML files, because there is only one HTML file, and if it is modified, it must be reloaded
  2. Js files don’t feel very friendly with HMR
if (module.hot) {
  // Once module.hot is true, HMR is enabled.
  // Add the following additional JS code
  // Make the HMR function code take effect when the JS file is modified
  module.hot.accept('./print.js'.function() {
    The // method listens for changes to the print.js file
    // Once changes occur, other modules are not repackaged and built.
    // The following callback functions are executed
    print();// This is a function in a js file
  });
}

Copy the code

Optimize code debugging with source-Map

  • source-mapIs a technique that provides source code to post-build code mapping, which is simply a configuration file error prompt, configured in the configuration filedevtoolCan be
devServer: {},
target: 'web'.// Refresh in real time
devtool: "eval-source-map"
Copy the code

The configuration is directly under the export object

There are two options for devtool configuration, inline and inline

  • The difference between inline and external:
    1. Outgoing generates files, inlined does not
    2. Inline builds are faster, but the file size is larger

There are quite a few configuration options, and you can look directly at Devtool

The development environment

  • Need to consider fast, debugging more friendly
Speed is fast(eval>inline>cheap>…) The eval – being – souce – map and eval – source – the map
More debug friendly Souce-map and cheap-module-souce-map and cheap-souce-map

Eval-source-map (√)/eval-cheap-module-source-map is recommended

The production environment

  • Inlining makes code bigger, so it’s not used in production
source-map Provides accurate information about the error code and the error location of the source code
cheap-module-souce-map Provides accurate information about the error code and the error location of the source codeOnly accurate rows, not columns
nosources-source-map All hidden
hidden-source-map Hiding only the source code prompts post-build code error messages

Source-map (√)

Use oneOf to optimize packaging build speed

In the rules we wrote earlier, every file is judged by all rules, so this operation is not necessary

So we used oneOf to solve this problem and optimize our packaging code

All rules are wrapped in an oneof array. That is, the rules we wrote earlier are placed in the oneof array, and the oneof array is placed in the Rules array object

rules: [
	{
		oneOf:[... related loader]}]Copy the code

If you need to match more than two times, you need to place the corresponding loader outside the oneOf array at the same level as the existing object, you can use the Enforce: ‘pre’ attribute to take precedence


Many people say that using vue scaffolding, it can be easily solved, so I think webpack learning here first, has spent too much time, need to learn some other things, or do some demo to practice the following!

conclusion

It took me a long time to learn Webpack. I have also watched webpack videos of 4 or 5 teachers on B website, all of which are the same as I have watched, but what I have learned is very limited. Basically, they are some simple configuration tutorials, including some loader and plug-in installation. Although Webpack is really good, it can be said that learning Webpack in network videos is a big hole, many lecturers use webpack version is 4.x version, now in 2021, the general new installation is directly installed 5.X version, there are a lot of things discarded in the latest version. Led to break the code to follow the teacher’s process, there will be a lot of a lot of strange error, lead to the learning cycle infinite stretched, speak truth, I spent more than half the time to find how to solve these bugs, in each big developer community to find relevant solutions, is really looking for a needle in a haystack, although there are a lot of solutions, however, due to the time of the blog, This solution has also been officially abandoned (which is ridiculous), I think the most effective way to solve the problem is to check the official document Webpack. Although the official document is really official, I can’t read it at first, but after I read it more, I will find it is also understandable! In short, learning Webpack really needs a lot of energy, there are not understand the place to check the official documents, or check the blog.