Home > Web Front-end > JS Tutorial > Sharing of webpack's processing of styles

Sharing of webpack's processing of styles

小云云
Release: 2018-01-08 09:41:49
Original
1407 people have browsed it

This article mainly introduces the handling of styles by webpack. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor to take a look, I hope it can help everyone.

We can introduce style files into js


require('myStyle.css')
Copy after login

At this time we need to introduce the corresponding webpack loader to help us parse this code.

css-loader with style-loader

First of all, we can introduce css-loader and style-loader to handle the parsing of css. Among them, css-loader is used To parse css files, style-loader is used to embed css files into js files


var path = require('path')
module.exports = {
 context: path.join(__dirname, 'src')
 entry: './',
 module: {
 rules: [
  {
  test: /\.css$/,
  include: [
   path.join(__dirname, 'src')
  ],
  use: ['style-loader', 'css-loader']
  }
 ]
 },
 output: {
  path: path.join(__dirname, 'dist'),
  filename: '[name].bundle.[hash].js'
 }
}
Copy after login

In the above code, the parsing order is from right to left. First use css-loader to parse the css file, and then use style-loader to embed it into the js code.

If you use less to write styles, you need to use less-loader to compile the style files into css files first, and then continue to use css-loader and style-loader. In addition, the loader loader can omit the following -loader. So the above code can be abbreviated to


module: {
 rules: [
 {
  test: /\.css$/,
  include: [
  path.join(__dirname, 'src')
  ],
  use: ['style', 'css', 'less']
 }
 ]
}
Copy after login

Generally in the test environment, in order to compile css faster, this method will be used more often, but the js file compiled in this way It will be relatively large and not suitable for use in a production environment.

Compile into a separate file

The above approach will package css and js together to reduce the number of actual requests, but because the compiled js file is relatively large , a waste of bandwidth. Therefore, we use the extract-text-webpack-plugin plug-in to compile css files into independent files. We can use CDN to push this file to the node server, or load it on demand as appropriate, thereby optimizing the customer request link and accelerating page response.


var path = require('path'),
 ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
 context: path.join(__dirname, 'src'),
 entry: './',
 module: {
 rules: [{
  test: /\.css$/,
  include: [
  path.join(__dirname, 'src')
  ],
  use: ExtractTextPlugin.extract({
  fallback: 'style',
  use: 'css'
  })
 }]
 },
 output: {
  path: path.join(__dirname, 'dist'),
  filename: '[name].bundle.[hash].js'
 },
 plugins: [
 new ExtractTextPlugin('[name].css')
 ]
}
Copy after login

Through the above code, we use the extract-text-webpack-plugin plug-in to process all css files in the src directory, and first use the css-loader plug-in to parse out the css code , if the parsing fails, use the style-loader plug-in to parse, and finally generate the corresponding js file in the dist directory

Compatible with old browsers

In the past, when we wrote styles, Some styles require different prefixes for different browsers, such as -webkit-. Now that we have the build tool, we no longer need to pay attention to these prefixes. The build tool will automatically add these prefixes for us.

For webpack, we naturally think that we need to use loader or plugin to help us do these things. After checking, we found that autoprefixer-loader has been abandoned and is no longer maintained. It is recommended to use posscss

postcss is used for The js plug-in that converts css styles in js needs to be used with other plug-ins. This is the same as babel6. It is just a converter itself and does not provide code parsing function.

Here we need the autoprefixer plugin to add prefixes to our styles. First download the module.


npm install -D autoprefixer
Copy after login

Then you can configure webpack


var autoprefixer = require('autoprefixer')
module.exports = {
 ...
 module: {
 loaders: [
  ...
  {
  {
   test: /\.css$/,
   loader: ExtractTextPlugin.extract(["css", "postcss"])
  },
  }
 ]
 },
 postcss: [autoprefixer()],
 ...
}
Copy after login

Check the extracted style file and you will find that it has been added Prefix


a {
 display: flex;
}
/*compiles to:*/
a {
 display: -webkit-box;
 display: -webkit-flex;
 display: -ms-flexbox;
 display: flex
}
Copy after login

In addition, autoprefixer can also generate different prefix numbers according to the target browser version. For example, if most of the users of your application use a newer version browser, then you can configure the following.

postcss: [autoprefixer({ browsers: ['last 2 versions'] })] The generated style will be slightly different, it is still the above example


a {
 display: flex;
}
/*compiles to:*/
a {
 display: -webkit-flex;
 display: -ms-flexbox;
 display: flex;
}
Copy after login

Style Compression

To compress the code, we can use webpack's built-in plug-in UglifyJsPlugin, which can compress both js code and css code.


plugins: [
 ...
 new webpack.optimize.UglifyJsPlugin({
 compress: {
  warnings: false
 }
 }),
 ...
]
Copy after login

In fact, it cannot be said that it is compressing the css code. In essence, it is compressing the js code and then outputting this code to the css file.

Use CommonsChunkPlugin to extract public code

First of all, it must be clear that CommonsChunkPlugin is used when there are multiple entries, that is, when there are multiple entry files, these entry files There may be some common codes, and we can extract these common codes into independent files. It is very important to understand this. (It took me a long time to understand something, alas~~~~)

If the same css file is required in multiple entries, we can use CommonsChunkPlugin to extract these common style files into independent style file.


module.exports = {
 entry: {
 "A": "./src/entry.js",
 "B": "./src/entry2.js"
 },
 ...
 plugins: [
 new webpack.optimize.CommonsChunkPlugin({
 name: "commons", filename: "commons.js"
 }),
 ...
 ]
}
Copy after login

Of course, not only common css will be extracted here, but if there is common js code, it will also be extracted into commons.js. There is an interesting phenomenon here. The name of the extracted css file will be the value of name in the parameter, and the js file name will be the value of filename.

CommonsChunkPlugin seems to only extract modules that are common to all chunks. If there are the following dependencies


##

// entry1.js
var style1 = require('./style/myStyle.css')
var style2 = require('./style/style.css')

// entry2.js
require("./style/myStyle.css")
require("./style/myStyle2.css")

// entry3.js
require("./style/myStyle2.css")
Copy after login

After using the plug-in, you will find that there are no Generate commons.css file.

If we only need to take the common code of the first two chunks, we can do this

##

module.exports = {
 entry: {
 "A": "./src/entry.js",
 "B": "./src/entry2.js",
 "C": "./src/entry3.js"
 },
 ...
 plugins: [
 new webpack.optimize.CommonsChunkPlugin({
 name: "commons", filename: "commons.js", chunks: ['A', 'B']
 }),
 ...
 ]
}
Copy after login

Related recommendations:

How to use externals of webpack

How to use webpack to optimize resource methods and techniques

webpack performance optimization

The above is the detailed content of Sharing of webpack's processing of styles. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template