How should webpack handle styles?
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')
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' } }
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'] } ] }
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') ] }
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
Then you can configure webpack
var autoprefixer = require('autoprefixer') module.exports = { ... module: { loaders: [ ... { { test: /\.css$/, loader: ExtractTextPlugin.extract(["css", "postcss"]) }, } ] }, postcss: [autoprefixer()], ... }
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 }
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; }
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 } }), ... ]
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" }), ... ] }
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")
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'] }), ... ] }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





In macOS Sonoma, widgets don't have to be hidden off-screen or forgotten in the Notification Center panel like they did in previous versions of Apple's macOS. Instead, they can be placed directly on your Mac’s desktop – they’re also interactive. When not in use, macOS desktop widgets fade into the background in a monochrome style, reducing distractions and allowing you to focus on the task at hand in the active application or window. However, when you click on the desktop, they return to full color. If you prefer a drab look and want to retain that aspect of uniformity on your desktop, there's a way to make it permanent. The following steps demonstrate how it is done. Open the System Settings app

Vue is an excellent JavaScript framework that can help us quickly build interactive and efficient web applications. Vue3 is the latest version of Vue, which introduces many new features and functionality. Webpack is currently one of the most popular JavaScript module packagers and build tools, which can help us manage various resources in our projects. This article will introduce how to use Webpack to package and build Vue3 applications. 1. Install Webpack

Differences: 1. The startup speed of the webpack server is slower than that of Vite; because Vite does not require packaging when starting, there is no need to analyze module dependencies and compile, so the startup speed is very fast. 2. Vite hot update is faster than webpack; in terms of HRM of Vite, when the content of a certain module changes, just let the browser re-request the module. 3. Vite uses esbuild to pre-build dependencies, while webpack is based on node. 4. The ecology of Vite is not as good as webpack, and the loaders and plug-ins are not rich enough.

Guide to solving misaligned WordPress web pages In WordPress website development, sometimes we encounter web page elements that are misaligned. This may be due to screen sizes on different devices, browser compatibility, or improper CSS style settings. To solve this misalignment, we need to carefully analyze the problem, find possible causes, and debug and repair it step by step. This article will share some common WordPress web page misalignment problems and corresponding solutions, and provide specific code examples to help develop

With the continuous development of web development technology, front-end and back-end separation and modular development have become a widespread trend. PHP is a commonly used back-end language. When doing modular development, we need to use some tools to manage and package modules. Webpack is a very easy-to-use modular packaging tool. This article will introduce how to use PHP and webpack for modular development. 1. What is modular development? Modular development refers to decomposing a program into different independent modules. Each module has its own function.

CSS web page background image design: Create various background image styles and effects, specific code examples are required Summary: In web design, background images are an important visual element, which can effectively enhance the attractiveness and readability of the page. This article will introduce some common CSS background image design styles and effects, and provide corresponding code examples. Readers can select and apply these background image styles and effects according to their own needs and preferences to achieve better visual effects and user experience. Keywords: CSS, background image, design style, effect, code representation

Configuration method: 1. Use the import method to put the ES6 code into the packaged js code file; 2. Use the npm tool to install the babel-loader tool, the syntax is "npm install -D babel-loader @babel/core @babel/preset- env"; 3. Create the configuration file ".babelrc" of the babel tool and set the transcoding rules; 4. Configure the packaging rules in the webpack.config.js file.

As the complexity of modern web applications continues to increase, building excellent front-end engineering and plug-in systems has become increasingly important. With the popularity of Spring Boot and Webpack, they have become a perfect combination for building front-end projects and plug-in systems. SpringBoot is a Java framework that creates Java applications with minimal configuration requirements. It provides many useful features, such as automatic configuration, so that developers can build and deploy web applications faster and easier. W
