Now that we’ve looked at configuration in Webpack, let’s look at the loaders and plugins that are often used in production

All dependencies described below will omit the installation process and are directly NPM installation dependency names unless otherwise specified

babel

Although some browsers and Node.js already support ES6, they don’t fully use ES6 in their development because they don’t fully support all ES6 standards. Babel is a JavaScript compiler that can convert ES6 code into ES5 code. This can be done easily.

Access the Babel

The Babel import method is very simple, through the loader to import

module.exports = {
  module: {
    rules: [{test: /\.js$/,
        use: ['babel-loader'],
      },{
        // Note here that esLint and Babel are used together
        // ESLint takes precedence, otherwise it checks compiled code
        // Eslint also has its own.eslintrc configuration file, but if the file configuration is too long, it will not be posted here
        test: /\.js$/,
        use: ['eslint-loader'].enforce: 'pre'}},// output source-map to debug ES6 source code directly
  devtool: 'source-map'
};
Copy the code

Babel configuration

The introduction of Babel is simple, but it also has its own configuration, which you might see in some projects. A file like babelrc, which is the configuration file of Babel, is a JSON file in the following format

{
  "plugins": [["transform-runtime",
      {
        "polyfill": false}]],"presets": [["es2015",
      {
        "modules": false}]."stage-2"."react"]}Copy the code

The plugins attribute tells Babel which plug-ins to use, and plug-ins control how the code is transformed. The full name of the transform-runtime plugin is babel-plugin-transform-runtime, which must be installed to enable Babel to run properly

npm install -D babel-plugin-transform-runtime
Copy the code

The purpose of babel-plugin-transform-Runtime is to reduce redundant code. For example, when converting ES6 to ES5, the class extends extends syntax is converted to prototype syntax, and the _extends helper function is injected at compile time. This causes every file that uses the class extends syntax to be injected with duplicate _extent helper function code. Babel-plugin-transform-runtime replaces the injected helper function with an import statement

var _extent = require('babel-runtime/helpers/_extent');
Copy the code

So you also need to install Babel-Runtime, which replaces a piece of code with an import statement to reduce file space

The presets attribute tells Babel which new syntax features are being used in the source code being converted. A single preset supports a set of new syntax features, and multiple presets can be stacked.

More details about Babel configuration can be found on the official website

CSS preprocessor

Introducing preprocessors

Applicable to the processor can greatly speed up the development speed, now the market common preprocessor SCSS, LESS, Sylus, etc., their use method no longer say more, want to see can click the link to my previous, take less as an example

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

Use the CSS -loader to find import statements such as @import and URL () in the CSS code and tell Webpack to rely on these resources. Style-loader will convert the CSS code into a string and inject it into JavaScript code to add styles to the DOM. Note: Less-loader depends on less. Install less when installing less-loader

If you don’t want to embed all the styles in HTML, you can use plug-ins to separate CSS. The ExtractTextPlugin was used before, but now the MiniCssExtractPlugin is used. Many of the old tutorials used the ExtractTextPlugin and had problems. Just switch to MiniCssExtractPlugin.

Separate separate CSS

Style-loader is responsible for embedding styles in HTML. Since we want to separate CSS, we need to use the Loader provided by the MiniCssExtractPlugin to handle styles

module: {
  rules: [{test: /\.less$/,
      use : [
        	MiniCssExtractPlugin.loader,
        	'css-loader'.'less.loader']]}},plugins: [
  new MiniCssExtractPlugin({
    filename: "css/style.css"}),]Copy the code

Auto-compatible browser

It’s also a headache for er to be compatible with different browser platforms, but postCSS helps automate compatibility with different browsers

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

Postcss automatically finds.postcSSrc files at runtime, plugins are specified as keys, and options are defined using the value of the object

{
  "modules": true."plugins": {
    "autoprefixer": {
      "grid": true}}}Copy the code

Plug-ins need to be installed separately

You can also configure the browser list in package.json

"browserslist": [
  "defaults"."not ie < 11"."last 2 versions"."1%" >."iOS 7"."last 3 iOS versions"].Copy the code

For more information, read this article zhihu

Processing images

base64

Almost every page has image elements. To handle image elements, we can use url-loader to convert images to Base64. After exceeding the limit, we can use file-loader. File-loader can replace JavaScript and CSS statements that import images with the correct address, and output the file to the corresponding location.

  module: {
    rules: [{test: /\.(gif|png|jpe? g|svg|webp)$/,
        use: [{
          loader: 'url-loader'.options: {
            // url-loader is used for files smaller than 30KB
            limit: 1024 * 30.// Otherwise, use file-loader
            fallback: 'file-loader',}}]}]},Copy the code

The compressed image

Image-webpack-loader can also be used to compress images

  module: {
    rules: [{test: /\.(gif|png|jpe? g|svg|webp)$/,
        use: [{
          loader: 'url-loader'.options: {
            // url-loader is used for files smaller than 30KB
            limit: 1024 * 30.// Otherwise, use file-loader
            fallback: 'file-loader',}}, {loader: 'image-webpack-loader'.options: {
              mozjpeg: { // Compress the JPEG configuration
                progressive: true.quality: 65
              },
              optipng: { // Use imagemin-optipng to compress PNG, enable: false to disable PNG compression
                enabled: false,},pngquant: { // Use imagemin-pngquant to compress PNG
                quality: '65-90'.speed: 4
              },
              gifsicle: { // Compress the GIF configuration
                interlaced: false,},webp: { // Enable webp to compress JPG and PNG images into WebP format
                quality: 75}}}]}},Copy the code

Sprite figure

If your page contains a lot of icon small ICONS, you can use the form of Sprites (CSS Sprites) with CSS background positioning to reduce image loading, but Sprite is not easy to maintain, every time new ICONS need to be re-made, then there is no “lazy way”, there is!! Webpack is “universal” and the SpritesmithPlugin can do this for us

resolve: {
  modules: [
    'node_modules'.'assets/sprite' // CSS where can I find Sprite diagrams]},plugins: [
  new SpritesmithPlugin({
    src: {
      cwd: path.resolve(__dirname, 'src/ico'),  // Ready to merge into sprit images folder
      glob: '*.png'  // What kind of pictures
    },
    target: {
      image: path.resolve(__dirname, 'src/assets/sprites.png'),  // Sprite image save path
      css: path.resolve(__dirname, 'src/assets/_sprites.scss')  // Where is the generated sass stored
    },
    apiOptions: {
      cssImageRef: "~sprite.png" // CSS follow this guide to find the Sprite diagram}})]Copy the code

Then you can use it in your project

@import './assets/sprite/_sprite.scss';

.open-icon{ 
    @include sprite($open); 
}
Copy the code

Difference between Sprite and Base64: It is recommended to use Sprite when there are too many small ICONS, and base64 when there are too few ICONS

HTML template

You can use the HTMl-webpack-plugin to generate HTML files, and the compiled dependencies are automatically injected

  plugins: [
    new HtmlWebpackPlugin({
      template: 'assets/index.html'.// Configuration file template}),].Copy the code

This article is part of the “Gold Nuggets For Free!” Event, click to view details of the event