[First understanding of webpack] built-in module path; common API of path; Webpack (use premise + default packaging + create partial + configuration file + write and package CSS file + write and package LESS file + postcss tool to process CSS)

1_ Know webpack

1.1_ built-in module path

The path module is used to process paths and files, providing many useful methods.

The paths on Mac OS, Linux and windows are different

  • \ or \ will be used as the separator of the file path on the window, of course / is also supported at present;
  • Use / as the separator of the file path on the Unix operating system of Mac OS and Linux;

What if an application is developed on Windows using \ as a delimiter and deployed to Linux?

  • There will be some problems with the display path;
  • In order to shield the differences between them, the path module can be used for path operations during development;

Portable Operating System Interface (POSIX)

  • Both Linux and Mac OS implement the POSIX interface;
  • Some Windows computers implement the POSIX interface;

1.2_path common API

Get information from path

  • dirname: Get the parent folder of the file;
  • basename: get the file name;
  • extname: get the file extension;
const path = require("path")
const filepath = "C://abc/cba/nba.txt"

// 可以从一个路径中获取一些信息
console.log(path.extname(filepath)) //.txt 
console.log(path.basename(filepath))  //nba.txt
console.log(path.dirname(filepath)) //C://abc/cba

Concatenation of paths:path.join

  • If you want to splice multiple paths, but different operating systems may use different separators;
  • At this time, you can use the path.join function;

Splicing absolute paths:path.resolve

  • The path.resolve() method resolves a path or sequence of path fragments into an absolute path;
  • The sequence of paths given isright to leftprocessed, each subsequent path is parsed in turn until an absolute path is constructed;
  • If an absolute path has not been generated after processing all segments of the given path, the current working directory is used;
  • Generated paths are normalized with trailing slashes removed, and zero-length path segments are ignored;
  • If no path segment is passed, path.resolve() will return the absolute path of the current working directory;
const path1 = "/abc/cba"
const path2 = "../hhh/kobe/james.txt"
console.log(path1 + path2)  ///abc/cba../hhh/kobe/james.txt

// 将多个路径拼接在一起: path.join
console.log(path.join(path1, path2))  //\abc\hhh\kobe\james.txt

1.3_ Understanding webpack

In fact, with the rapid development of the front-end, the development of the front-end has become more and more complicated:

  • For example, the development process needs to be developed in a modular way;
  • For example, use some advanced features to speed up development efficiency or security, such as developing script logic through ES6+ and TypeScript, and writing css style code through sass and less;
  • For example, during the development process, it is also hoped to monitor the changes of files in real time and reflect them on the browser to improve the efficiency of development;
  • For example, after the development is completed, the code needs to be compressed, merged, and other related optimizations, etc...

But for many front-end developers, there is no need to think about these problems, and they are not faced with these problems at all in daily development:

  • This is because the current front-end development usually directly uses three major frameworks for development: Vue, React, Angular;
  • But in fact, the creation process of these three frameworks is all with the help of scaffolding (CLI);
  • In fact, Vue-CLI, create-react-app, and Angular-CLI are all based on webpack to help support modularization, less, TypeScript, packaging optimization, etc.;

Vue-CLI, create-react-app, and Angular-CLI all rely on webpack for scaffolding


The official explanation of webpack concept : webpack is a static module bundler for modern JavaScript applications.

webpack is a static modular packaging tool for modern JavaScript applications;
detailed disassembly:

  • Packaging bundler: webpack can help package, so it is a packaging tool
  • Static static: The reason for this expression is that the code can eventually be packaged into the final static resource (deployed to the static server);
  • Modular module: webpack supports various modular development by default, ES Module, CommonJS, AMD, etc.;
  • Modern modern: The front end said that it is precisely because modern front-end development faces various problems that the emergence and development of webpack has been born;

insert image description here


2_webpack basic packaging

2.1 Prerequisites for using Webpack

webpack's official website

The operation of Webpack depends on the Node environment, so there must be a Node environment on the computer

  • Install Node.js first, and npm will be installed at the same time;
  • Node's official website

2.2_Webpack's default packaging

Package through webpack, then run the packaged code, and execute the command directly in the directory:webpack

generate adist folder, which stores amain.js file, which is the packaged file:

  • The code in this file is minified and uglified;
  • In addition, it is found that ES6 syntax still exists in the code, such as arrow function, const, etc. This is because by default, webpack does not know whether the packaged file needs to be converted to the syntax before ES5, and it needs to be converted and set through babel;

Although it can be packaged normally, how does webpack determine the entry?

  • In fact, when running webpack, webpack will look for src/index.js in the current directory as the entry point;
  • Therefore, if the src/index.js file does not exist in the current project, an error will be reported;

Of course, you can also specify the entry and exit through configuration

npx webpack --entry ./src/main.js --output-path ./build


2.3_ Create a partial webpack

The previous direct execution of the webpack command uses the global webpack. If you want to use the local one, you can follow the steps below.
Step 1: Create a package.json file to manage project information, library dependencies, etc.

npm init

Step 2: Install partial webpack

npm install webpack webpack-cli -D

Step 3: Use partial webpack

npx webpack

Step 4: Create the scripts script in package.json and execute the script packaging

npm run build

"scripts":{
    
    
   "build": "webpack "
}

3_Webpack configuration file

Under normal circumstances, the projects that webpack needs to package are very complex and require a series of configurations to meet the requirements. The default configuration is definitely not possible.

You can create a webpack.config.js file in the root directory as the webpack configuration file:
continue to execute the webpack command, and you can still package normally npm run build

specify configuration file

What if the name of the configuration file is not webpack.config.js, but something else?

  • For example, modify webpack.config.js to wk.config.js;

  • At this time, you can specify the corresponding configuration file through --config;

    webpack --config wk.config.js

But every time you execute the command to compile the source code, it will be very cumbersome, so you can add a new script to package.json:
specify the configuration file

  "scripts" : {
    
    
  	"build"  : "webpack --config wk .config.js"
   }

Then execute npm run buildto package.


4_Writing and packaging CSS files

Let's look at a case first. Create a component.js, create an element through JavaScript, and want to set the CSS style for it; found that the packaging error (module loading failed) is related to the css file, and there is a lack of a suitable Loader

insert image description here


4.1 Use of _css-loader

The above error message tells that a loader is needed to load the css file, but what is the loader?

  • loader can be used to transform the source code of the module;
  • The css file is also regarded as a module, which is loaded through import;
  • When loading this module, webpack does not actually know how to load it, and must formulate a corresponding loader to complete this function;

What kind of loader is needed?

  • For loading css files, a loader that can read css files is needed;
  • The most commonly used loader is css-loader;

css-loader installation: npm install css-loader -D


4.2 Usage scheme of css-loader

Three ways to load css files using loader:

  • inline method;
  • CLI mode (no longer used in webpack5);
  • Configuration method;,

Inline mode: The inline mode is less used because it is inconvenient to manage;

  • Add the loader used before the imported style, and use ! to split;

CLI mode

  • In the documentation of webpack5, there is no --module-bind;
  • It is also rarely used in practical applications because it is inconvenient to manage;

4.3_loader configuration method

The meaning of the configuration mode is inwebpack.config.jsThe configuration information is written in the file:

  • Multiple loaders are allowed in module.rules (because other loaders will continue to be used to load other files);
  • This method can better represent the configuration of the loader, and is also convenient for later maintenance. At the same time, it also allows you to have a global overview of each Loader;

The configuration of module.rules is as follows:

(1) The value corresponding to the rules attribute is an array: [Rule]

(2) Each Rule is stored in the array, and a Rule is an object, and multiple attributes can be set in the object:

  • test attribute: used to match resources (resources), usually set to regular expressions;
  • use attribute: the corresponding value is an array: [UseEntry]. Note that UseEntry is an object, and some other properties can be set through the properties of the object
    • loader: There must be a loader attribute, and the corresponding value is a string;
    • options: optional attribute, the value is a string or object, and the value will be passed to the loader;
    • query: options have been used instead;
  • Passing a string (such as: use: [ 'style-loader' ]) is a shorthand for the loader attribute (such as: use: [ { loader: 'style-loader'} ]);
  • loader attribute: Shorthand for Rule.use: [ { loader } ]
const path = require("path")

module.exports = {
    
    
  entry: "./src/main.js",
  output: {
    
    
    filename: "bundle.js",
    path: path.resolve(__dirname, "./build")
  },
  module: {
    
    
  rules: [
      {
    
    
        test: /\.css$/,	// 正则表达式:告诉webpack匹配什么文件
        use: [ // use中多个loader的使用顺序是从后往前
          {
    
     loader: "style-loader" },
          {
    
     loader: "css-loader" }
        ]
      }
 }     

4.4_style-loader

Although the css file can be loaded by css-loader, the css does not actually take effect in the code (the page has no effect).

Why is this?

  • Because css-loader is only responsible for parsing the .css file, and will not insert the parsed css into the page;
  • If you want to complete the operation of inserting style, then you need another loader, which is style-loader;

Install style-loader: npm install style-loader -D

Configure style-loader

How to use style-loader:

  • In the configuration file, add style-loader;
  • Note: Because the execution order of the loader is from right to left (or from bottom to top, or from back to front), it is necessary to write style-loader in front of css-loader;

Execute and compile npm run build again, and you can find that the packaged css has taken effect:

  • The current css is added through the in-page style;
  • Follow-up will also talk about how to extract css into a separate file and perform operations such as compression;

5_Writing and packaging LESS files

5.1_Introduction

During development, less, sass, and stylus preprocessors may be used to write css styles, which will be more efficient.

How to make the environment support these preprocessors?
First of all, you need to make sure that the css written by less, sass, etc. needs to be converted into ordinary css through tools;

For example, write the following less style

title.less

@fontSize: 50px;
@fontColor: blue;

.title {
  font-size: @fontSize;
  color: @fontColor;
  user-select: none;
}

5.2_Less tool processing

Enter the terminal command: npm install less -D

Combined with the above case, enter the terminal command

npx lessc ./src/css/title.less title.css

5.3_less-loader processing

A lot of css will be written in the project, how can they be automatically converted? At this time, you can use less-loader to automatically use the less tool to convert less to css;

npm install less-loader -D

Configure webpack.config.js

  module: {
    
    
  rules: [
      {
    
    
        test: /\.less$/,	// 正则表达式:告诉webpack匹配什么文件
        use: [ // use中多个loader的使用顺序是从后往前
          {
    
     loader: "style-loader" },
          {
    
     loader: "css-loader" },
          {
    
     loader: "less-loader" }
        ]
      }

Execute npm run build, less can be automatically converted to css, and the page will also take effect


6_postcss tool to process CSS

6.1_ Know PostCSS tools

What is PostCSS?

  • PostCSS is a tool for transforming styles through JavaScript;
  • This tool can help with some CSS transformations and adaptations, such as automatically adding browser prefixes and resetting CSS styles;
  • But to realize these functions, you need to use the corresponding plug-ins of PostCSS;

How to use PostCSS? There are mainly two steps:

  • Step 1: Find PostCSS extensions in build tools, such as postcss-loader in webpack;
  • Step 2: Choose to add the PostCSS related plug-ins you need;

6.2_postcss-loader

You can use the construction tool: using postcss in webpack is handled by postcss-loader;

Install postcss-loader: npm install postcss-loader -D

Modify the loader that loads css: (there are too many configuration files, a part is given)

Note: Because postcss needs a corresponding plugin to work, you need to configure its plugin;


  module: {
    
    
    rules: [
      {
    
           
        test: /\.css$/,	 // 正则表达式:告诉webpack匹配什么文件
        use: [ // use中多个loader的使用顺序是从后往前
          {
    
     loader: "style-loader" },
          {
    
     loader: "css-loader" }
        ],
        // 简写一: 如果loader只有一个
        // loader: "css-loader"
        // 简写二: 多个loader不需要其他属性时, 可以直接写loader字符串形式
        use: [ 
          "style-loader",
          "css-loader", 
          "postcss-loader"
          // {	//此处注释的内容,按照相同的作用迁移到postcss.config.js
          //   loader: "postcss-loader",
          //   options: {
    
    
          //     postcssOptions: {
    
    
          //       plugins: [
          //         "autoprefixer"
          //       ]
          //     }
          //   }
          // }
        ]
      },
      {
    
    
        test: /\.less$/,
        use: [ "style-loader", "css-loader", "less-loader", "postcss-loader" ]
      }
    ]
  }

6.3_ Separate postcss configuration file

To add a prefix, you need to install autoprefixer: npm install autoprefixer -D

These configuration information can be managed in a separate file: create postcss.config.js in the root directory

module.exports = {
    
    
  plugins: [
    "autoprefixer"
  ]
}

6.5_postcss-preset-env

In fact, configuring the plugin does not require autoprefixer when configuring postcss-loader. Another plugin can be used: postcss-preset-env

  • postcss-preset-env is also a postcss plugin;
  • It can help convert some modern CSS features into CSS recognized by most browsers, and will add the required polyfill according to the target browser or runtime environment;
  • It also includes automatically helping to add autoprefixer (so it is equivalent to having built-in autoprefixer);

First, postcss-preset-env needs to be installed: npm install postcss-preset-env -D

After that, just modify the previous autoprefixer directly:

postcss.config.js

module.exports = {
    
    
  plugins: [
    "postcss-preset-env"
  ]
}

Note: When using some postcss plugins, you can also pass in strings directly

When using ss-loader, the configuration plugin does not need to use autoprefixer. Another plugin can be used: postcss-preset-env

  • postcss-preset-env is also a postcss plugin;
  • It can help convert some modern CSS features into CSS recognized by most browsers, and will add the required polyfill according to the target browser or runtime environment;
  • It also includes automatically helping to add autoprefixer (so it is equivalent to having built-in autoprefixer);

First, postcss-preset-env needs to be installed: npm install postcss-preset-env -D

After that, just modify the previous autoprefixer directly:

postcss.config.js

module.exports = {
    
    
  plugins: [
    "postcss-preset-env"
  ]
}

Note: When using some postcss plugins, you can also pass in strings directly

Guess you like

Origin blog.csdn.net/qq_54075517/article/details/132034668