“This is the 14th day of my participation in the First Challenge 2022.

Postcss plugin for Autoprefixer

Autoprefixer automatically prefixes CSS properties using can I use data.

But that doesn’t work yet, so you need to set up Browserslist, the target set of browsers, the compatible version of the browser, and the tool that uses the browserslist will specifically output the compatible code based on browserslist’s description.

Browserslist can be set up in two ways.

You can add properties directly to the package.json file as follows

  "browserslist": [
    "1%" >."last 2 versions"
  ]
Copy the code

You can also create a.browserslistrc file in the root directory and write it directly, without parentheses.

// .browserslistrc
>1%
last 2 versions
Copy the code
  • >1% : browsers with a global market share of more than 1%.
  • Last 2 Versions: indicates the latest two major versions of compatible browsers.

You can use NPX Browserslist to query for compatible browser versions.

Postcss plugin CSsnano

Compress the CSS code.

mini-css-extract-plugin

Pull out the CSS code into a separate file, you can specify the filename, support absolute path, will automatically generate folders. Replace style-loader with minicss.loader where loader is written.

// webpack.config.js
const minicss = require("mini-css-extract-plugin")
module.exports = {
  plugins: [
    new minicss({
      filename: 'style/index.css'})].module: {
    rules: [{test: /\.less$/,
        use: [
          minicss.loader,
          {
            loader: "css-loader".options: {
              modules: true}}, {loader: 'postcss-loader'}, {loader: 'less-loader',}]}]}Copy the code

clean-webpack-plugin

Clean up the packing directory before each packing.

// webpack.config.js
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
  plugins: [
     newCleanWebpackPlugin ()],}Copy the code

Implement a custom Loader

The loader reference

Create a myLoaders/a-loader.js file in the root directory and import it in the Module using an absolute path.

// webpack.config.js
module: {
    rules: [{test: /\.js$/,
        use: [
         {
            loader: path.resolve(__dirname, './myLoaders/a-loader.js'),},]},]}Copy the code

The structure of the loader

Loader is a function. Take source, which is the content of the module that matches the test re, in this case the.js file.

  • This function cannot beArrow functionBecause thewebpackprovidesloader apiIt’s all mounted tothisOn the.
  • This function must return a value or an error will be reported.
// a-loader.js
module.exports = function(source) {
  console.log('🚀 🚀 ~ source:', source);
  return source
}
Copy the code

The SRC /index.js file outputs only one line of logs.

// src/index.js
console.log('hello, world');
Copy the code

Source is the SRC /index.js file that has not been compiled by Webpack.