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

Sharing of webpack's processing of styles

Jan 08, 2018 am 09:41 AM
web webpack share

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to share Quark Netdisk to Baidu Netdisk? How to share Quark Netdisk to Baidu Netdisk? Mar 14, 2024 pm 04:40 PM

Quark Netdisk and Baidu Netdisk are very convenient storage tools. Many users are asking whether these two softwares are interoperable? How to share Quark Netdisk to Baidu Netdisk? Let this site introduce to users in detail how to save Quark network disk files to Baidu network disk. How to save files from Quark Network Disk to Baidu Network Disk Method 1. If you want to know how to transfer files from Quark Network Disk to Baidu Network Disk, first download the files that need to be saved on Quark Network Disk, and then open the Baidu Network Disk client. , select the folder where the compressed file is to be saved, and double-click to open the folder. 2. After opening the folder, click "Upload" in the upper left corner of the window. 3. Find the compressed file that needs to be uploaded on your computer and click to select it.

How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments Mar 25, 2024 am 11:41 AM

1. First, we enter NetEase Cloud Music, and then click on the software homepage interface to enter the song playback interface. 2. Then in the song playback interface, find the sharing function button in the upper right corner, as shown in the red box in the figure below, click to select the sharing channel; in the sharing channel, click the "Share to" option at the bottom, and then select the first "WeChat Moments" allows you to share content to WeChat Moments.

How to share files with friends on Baidu Netdisk How to share files with friends on Baidu Netdisk Mar 25, 2024 pm 06:52 PM

Recently, Baidu Netdisk Android client has ushered in a new version 8.0.0. This version not only brings many changes, but also adds many practical functions. Among them, the most eye-catching is the enhancement of the folder sharing function. Now, users can easily invite friends to join and share important files in work and life, achieving more convenient collaboration and sharing. So how do you share the files you need to share with your friends? Below, the editor of this site will give you a detailed introduction. I hope it can help you! 1) Open Baidu Cloud APP, first click to select the relevant folder on the homepage, and then click the [...] icon in the upper right corner of the interface; (as shown below) 2) Then click [+] in the "Shared Members" column 】, and finally check all

Mango tv member account sharing 2023 Mango tv member account sharing 2023 Feb 07, 2024 pm 02:27 PM

Mango TV has various types of movies, TV series, variety shows and other resources, and users can freely choose to watch them. Mango TV members can not only watch all VIP dramas, but also set the highest definition picture quality to help users watch dramas happily. Below, the editor will bring you some free Mango TV membership accounts for users to use, hurry up and take a look Take a look. Mango TV latest member account free sharing 2023: Note: These are the latest member accounts collected, you can log in directly and use them, do not change the password at will. Account number: 13842025699 Password: qds373 Account number: 15804882888 Password: evr6982 Account number: 13330925667 Password: jgqae Account number: 1703

Solve the problem that Discuz WeChat sharing cannot be displayed Solve the problem that Discuz WeChat sharing cannot be displayed Mar 09, 2024 pm 03:39 PM

Title: To solve the problem that Discuz WeChat shares cannot be displayed, specific code examples are needed. With the development of the mobile Internet, WeChat has become an indispensable part of people's daily lives. In website development, in order to improve user experience and expand website exposure, many websites will integrate WeChat sharing functions, allowing users to easily share website content to Moments or WeChat groups. However, sometimes when using open source forum systems such as Discuz, you will encounter the problem that WeChat shares cannot be displayed, which brings certain difficulties to the user experience.

What are web standards? What are web standards? Oct 18, 2023 pm 05:24 PM

Web standards are a set of specifications and guidelines developed by W3C and other related organizations. It includes standardization of HTML, CSS, JavaScript, DOM, Web accessibility and performance optimization. By following these standards, the compatibility of pages can be improved. , accessibility, maintainability and performance. The goal of web standards is to enable web content to be displayed and interacted consistently on different platforms, browsers and devices, providing better user experience and development efficiency.

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

what does web mean what does web mean Jan 09, 2024 pm 04:50 PM

The web is a global wide area network, also known as the World Wide Web, which is an application form of the Internet. The Web is an information system based on hypertext and hypermedia, which allows users to browse and obtain information by jumping between different web pages through hyperlinks. The basis of the Web is the Internet, which uses unified and standardized protocols and languages ​​to enable data exchange and information sharing between different computers.

See all articles