Webpack combat (D): teach you how to easily get - preprocessor (loader)

The previous three sessions, I mainly to share some knowledge about the configuration webpack, and how to package js file, and if we encounter other types of resources such as images, css, font font, and so on, how do we deal with it? Today will introduce pre-processor (loader), it gives the ability Webpack can handle different types of resources, greatly enriched its scalability.

If you want to know the basic configuration Webpack can refer to the following address:

Webpack actual (a): Webpack strapping tools and installation parameters

Webpack combat (b): Introduction and usage of webpack-dev-server

Webpack combat (c): as a front end Webpack resources inlet and outlet configurations you can not understand

In one project, we have to face a variety of resources, how to make a good deal Webpack these resources? This time we need the help of pre-processor (loader), loader literally means the loader, in Webpack it functions more like an actual preprocessor. Webpack itself only know JavaScript, there are other types of resources must be defined a plurality of loader or its translation, the output is capable of receiving Webpack form before proceeding, and therefore do loader is actually a pre-work.

loader configuration

  1. loader introduced
    if we are going to introduce css files, webpack is not treated as
// common.css
body {
  font-size: 20px;
  background: #0fc;
}
//index.js
import './common.css'

Here Insert Picture Description
FIG executed as a result, we can see, is unable to process Webpack css files, we need to pre-install css-loader. Installation steps

npm install --save-dev css-loader

Then we will introduce a program loader, configure webpack.config.js configuration is as follows:

const path = require('path')
module.exports = {
  context: path.join(__dirname, './src'),
  entry: {
    index: './index.js'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'index.js'
  },
  mode: 'development'
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [ 'css-loader'],
      },
    ],
  }
}

Associated with the object loader disposed in the module, which represents the processing rules module.rules module. Each rule can contain many internal configuration items, here we use only the two most important -test and use.

  • test may receive a regular expression or a regular array elements expression, the only positive match on the module will use this rule. As to /.css$/ to match all files ending in .css.
  • use may be received as an array comprising a loader used by the rule may be a string objects.

Many times, when dealing with a certain type of resources we need to use multiple loader. Such as, for SCSS types of resources, we need to sass-loader to handle its syntax and compiles it into CSS; then using css-loader handling all kinds of loads CSS syntax; finally using style-loader to the character style style label insertion string packaged page.
Following introduction of style-loader, install command as follows:

npm install --save-dev style-loader

Configuration code is as follows:

const path = require('path')
module.exports = {
  context: path.join(__dirname, './src'),
  entry: {
    index: './index.js'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'index.js'
  },
  mode: 'development'
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
    ],
  }
}

Until then packaged, the style will be effective, you should see a page insert a style tag contains style CSS files, so we finished loading the configuration file from JS CSS file.
Packing the following picture:
Here Insert Picture Description
operating results below
Here Insert Picture Description
the style-loader on the front css-loader, because it is packaged in Webpack array to the left in the order from the right to the resource loader process, thus in effect should last on the left.

loader as a pre-processor configuration items will usually provide some developers, at the time of introduction loader you can pass them by options

module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 
          {
            loader: 'css-loader',
            options: {
              // 有关css-loader的配置
            }
          }
        ],
      },
    ],
  }
  1. Other configurations
    exclude are used to include or exclude the specified directory contains modules, can receive a regular expression or a character string (file absolute path), and they are composed of an array of
module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
        exclude: /node_modules/
      },
    ],
  }

The node_modules within the module does not exclude the implementation of the rules in this rule. The configuration items usually will be added, or it may slow down the speed of the overall package.

module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
        include: /src/
      },
    ],
  }

include representatives of the rule only to the regular matching of modules to take effect. If we set the project will include the source directory, and other directories node_modules will naturally ruled out.

If you exclude and include exist, then exclude higher authority

and issuer resource can be used to more accurately determine the scope rules module, in Webpack, we believe that a resource module is loaded, and the loader is issuer

 module: {
    rules: [
      {
        use: ['style-loader', 'css-loader'],
        resource: {
          test: /\.css$/i,
          exclude: /node_modules/
        },
        issuer: {
          test: /\.js$/i,
          exclude: /node_modules/
        }
      },
    ],
  }

通过添加resource对象来将外层的配置包起来,区分了resource和issuer中的规则,这样就一目了然了。

enforce用来指定一个loader的种类,只接收“pre”或“post”两种字符串类型的值。事实上,我们也可以不使用enforce而只要保证loader顺序是正确的即可。配置enforce主要的目的是使模块规则更加清晰,可读性更强,尤其是在实际工程中,配置文件可能达到上百行的情况,难以保证各个loader都按照预想的方式工作,使用enforce可以强制指定loader的作用顺序。

常用的预处理器

  1. babel-loader用来处理ES6+并将其编译为ES5,它使我们能够在工程中使用最新的语言特性,同时不必特别关注这些特性在不同平台的兼容问题。
npm install babel-loader babel-core babel-preset-env
  • babel-loader:它是使Babel与Webpack协同工作的模块。
  • babel-core:顾名思义,它是Babel编译器的核心模块。
  • babel-preset-env:它是Babel官方推荐的预置器,可根据用户设置的目标环境自动添加所需的插件和补丁来编译ES6+代码。
    配置文件如下:
 {
      test: /\.js$/,
      exclude: /(node_modules|bower_components)/,
      use: {
        loader: 'babel-loader',
        options: {
          cacheDirectory: true,
          presets: [
            [
              'env', {
                modules: false
              }
            ]
          ]
        }
      }
    }

由于babel文件很大没,所以要排除node_modules|bower_components
对于babel-loader本身我们添加了cacheDirectory配置项,它会启用缓存机制,在重复打包未改变过的模块时防止二次编译,同样也会加快打包的速度
babel-loader支持从.babelrc文件读取Babel配置,因此可以将presets和plugins从Webpack配置文件中提取出来,也能达到相同的效果。

  1. ts-loader
    ts-loader与babel-loader的性质类似,它是用于连接Webpack与Typescript的模块,安装命令如下:
npm install ts-loader typescript

webapck.config.js配置如下

rules: [
	{
	test: /\.ts$/,
	use:'ts-loader' 
	}
]
  1. Loader-HTML
    HTML-Loader is used to convert the string to the HTML file and format, which allows us to load an HTML fragments coming JS.
  2. Loader-handlebars
    handlebars-Loader to handle handlebars template, when you want to install additional installation handlebars.
  3. Loader-File
    File Loader for resource-packed file types, and returns its publicPath.

to sum up

About Webpack preprocessor (loader) here temporarily analysis, which represent the personal views, welcome Paizhuan To learn more, please scan the following:

Here Insert Picture Description

Published 244 original articles · won praise 115 · views 420 000 +

Guess you like

Origin blog.csdn.net/yilanyoumeng3/article/details/103998933