Home > Web Front-end > JS Tutorial > Package css styles separately in webpack

Package css styles separately in webpack

php中世界最好的语言
Release: 2018-06-13 11:46:32
Original
2408 people have browsed it

This time I will bring you the separate packaging of CSS styles in webpack. What are the precautions for packaging CSS styles separately in webpack? The following is a practical case, let's take a look.

Zero, introduction

The following are some basic knowledge summarized in personal projects. Record them here to deepen your impression and let others know. Everyone can understand webpack more quickly and conveniently, and use it. Due to limited capabilities, if there are errors or problems, please help point them out.

Webpack treats all resources as a module. CSS, Image, and JS font files are all resources and can be packaged into a bundle.js file.

The basic use of webpack is very simple, but it would be a lot to explain all aspects, so here we mainly explain how to use webpack to package css separately.

As for packaging, how to add a hash value, how to replace the reference path in HTML, and how to upload to CND can be achieved using gulp. [Write an article later if you are interested]

1. Extract-text-webpack-plugin usage

Package css separately, in webpack You need to use a plug-in, extract-text-webpack-plugin

1. Install extract-text-webpack-plugin

// use npm 
npm install extract-text-webpack-plugin --save-dev
// or use yarn 
yarn add extract-text-webpack-plugin
Copy after login

2. Configuration

Write the configuration of the plug-in in the loader (what loader to use), and set the name of the extracted CSS file in the plugins of webpack.

var Ex = require('extract-text-webpack-plugin');
// ...省略
module: {
 loaders: [{
  test: /\.less/,
  loader: Ex.extract('style-loader', 'css-loader','less-loader') // 单独打包出CSS,这里配置注意下
 }]
},
plugins: [
 new Ex("【name】.css")
]
Copy after login

For a little more detail, you can refer to this "Usage and Installation of extract-text-webpack-plugin"

Here are two actual usage examples to facilitate everyone's understanding

2. Single-page application, package the CSS in JS separately

To package a file, you only need to reference the css file in the regular entry js file. To package into multiple CSS files, you can set multiple CSS entries and let webpack use loader to package them. It is the same as splitting and packaging js files separately. Here are two examples.

// webpack 1.x 配置  【早期使用的配置,那时候是1.x】
/*  webpack.config.js  */
var precss = require('precss');
var cssnext = require('cssnext');
var autoprefixer = require('autoprefixer');
var cssnano = require('cssnano');
var Ex = require('extract-text-webpack-plugin');
module.exports = {
  entry: './index.js',
  output: {
   filename: 'index.js'
  },
  module: {
   loaders: [{
    test: /\.less/,
    loader: Ex.extract('style-loader', 'css-loader','less-loader') // 单独打包出CSS,这里配置注意下
   }]
  },
  plugins: [
   new Ex("【name】.css")
  ]
 }
Copy after login

3. How webpack packages multiple CSS files

2. Add the corresponding configuration to the configuration file

Provided directly below A completed multi-entry CSS packaging configuration

// webpack 3.x 的配置
var path = require('path')
var glob = require('globby') 
var webpack = require('webpack')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
// CSS入口配置
var CSS_PATH = {
 css: {
  pattern: ['./src/**/[^_]*.less', '!./src/old/**/*.less'],
  src: path.join(__dirname, 'src'),
  dst: path.resolve(__dirname, 'static/build/webpack'),
 }
}
// 遍历除所有需要打包的CSS文件路径
function getCSSEntries(config) {
 var fileList = glob.sync(config.pattern)
 return fileList.reduce(function (previous, current) {
  var filePath = path.parse(path.relative(config.src, current))
  var withoutSuffix = path.join(filePath.dir, filePath.name)
  previous[withoutSuffix] = path.resolve(__dirname, current)
  return previous
 }, {})
}
module.exports = [
 {
  devtool: 'cheap-module-eval-source-map',
  context: path.resolve(__dirname),
  entry: getCSSEntries(CSS_PATH.css),
  output: {
   path: CSS_PATH.css.dst,
   filename: '[name].css'
  },
  module: {
   rules: [
    {
     test: /\.less$/,
     use: ExtractTextPlugin.extract({
      use: ['css-loader', 'postcss-loader', 'less-loader']
     })
    }
   ]
  },
  resolve: {
   extensions: ['.less']
  },
  plugins: [
   new ExtractTextPlugin('[name].css'),
  ]
 },
// 如果还需要打包js,则可以在这里增加一个单独打包js的处理【根据自己需求来】
// {
//  entry:{},
//  output:{},
//  ... 省略
// }
]
Copy after login

Maybe some students are still using webpack1.x, so here is a simple configuration of webpack1.x

// webpack 1.x 版本
// ...其他配置和webpack3.x一样
module: {
  loaders: [
    {
      test: /\.less$/,
      loader: ExtractTextPlugin.extract("style-loader","css-loader","postcss-loader","less-loader")
    },
  ]
}
plugins: [
 new ExtractTextPlugin('[name].css'),
]
// ...其他配置和webpack3.x一样
Copy after login

I believe you have read the case in this article After mastering the method, please pay attention to other related articles on the php Chinese website for more exciting content!

Recommended reading:

Vue php handles cross-domain issues

apply Math.max() function usage

The above is the detailed content of Package css styles separately in webpack. 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