Webpack packs css separately

**

Goal: All css files in the project are packaged into the distfollowing cssfolder;

**


1. Webpack's processing of css

We all know that webpack can directly process javascript code, but for css, image, font, etc., it cannot be directly processed. It needs to loaderbe converted into javbascript code slices, and then processed.

For processing CSS, the loaders that need to be used are: style-loader, css-loader;
first download these loaders

command line execution

npm install style-loader css-loader --save-dev

After downloading, the webpack.config.jsconfiguration is as follows
In the module configuration, configure the loader option

module:{
    rules:[
      {
        test:/\.css$/,
        use:["style-loader","css-loader"]//注意:loader是从又往左开始加载处理的,所以先执行css-loader
      }
    ],
  },

But this will package the css into the corresponding js, then when the page is loaded, the js will be parsed first and then the css will be loaded, which will affect the user experience

So we need to extract the css separately and linkinject it into the file in the way

2. Use ExtractTextWebpackPlugin to extract css injection separately

Implementation needs to download the plugin

npm init

change webpack.config.jsconfiguration

const path = require('path');
const webpack = require('webpack')
//引入插件
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const configs = {
  entry:{
    'commom':['./src/page/common/index.js'],
    'index':['./src/page/index/index.js'],
    'login':['./src/page/login/index.js']
  },
  output:{
    path:path.resolve(__dirname, 'dist'),
    filename:'js/[name].js'
  },
  externals:{
    //可以把外部的变量或模块加载进来,比如cdn引入的jquery,想要按需模块化引入
     'jquery':'window.jQuery'
  },
  module:{
    rules:[
      {
        test:/\.css$/,
        //注意:这里还需要更改一下
        use:ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      }
    ]
  },
  plugins:[
    new webpack.optimize.CommonsChunkPlugin({
      name : 'common',
      filename : 'js/base.js'
    }),
    //这里会按照output的路径打包到css文件夹下面对应的css的名字
    new ExtractTextPlugin('css/[name].css')
  ]
}
module.exports= configs

In this way, all the css referenced in the entryentry file is packaged into a separate css file,

If your styles file size is large, this will do faster early loading because the CSS bundle will be loaded in parallel with the JS bundle.

Regarding the file packaging of less and sass, I won't describe it here. You can refer to
https://blog.csdn.net/lhtzbj12/article/details/79188447

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325857442&siteId=291194637