Home > Web Front-end > JS Tutorial > body text

How should webpack handle styles?

亚连
Release: 2018-06-13 15:10:25
Original
1462 people have browsed it

This article mainly introduces a brief discussion of webpack's processing of styles. Now I share it with you and give you a reference.

This article introduces the processing of styles by webpack and shares it with everyone. The details are as follows:

We can introduce style files in js

require('myStyle.css')
Copy after login

At this time we need to introduce the corresponding The webpack loader helps 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 out the css file After that, use style-loader to embed it into 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 will be relatively large, which is not suitable for 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 , wasting 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. First, use the css-loader plug-in to parse out the css code. If the parsing fails, use style-loader The plug-in parses and finally generates the corresponding js file in the dist directory

Compatible with old browsers

In the past when we wrote styles, some styles required different browsers to add different Prefix, 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

Look at the extracted style file and you will find that the prefix has been added

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 be used according to the target browser Versions generate different prefix numbers. For example, if most of the users of your application use a newer version of the browser, you can configure it as follows.

postcss: [autoprefixer({ browsers: ['last 2 versions'] })] This is the generated style, which will be a little different, or the above example

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

style Compression

We can use webpack's built-in plug-in UglifyJsPlugin to compress code, 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 the commons.css file is not generated at all.

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

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

About the child_process module in node (detailed tutorial)

What are the applications of child processes in Node.js Scenario

Detailed interpretation of the file system and stream in nodeJs

The above is the detailed content of How should webpack handle 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!