extract-text-webpack-plugin用法

一 背景
最近在作一个项目,项目自己是用vue-cli建立的单页面应用,因为项目扩展须要建立多页面,因此须要对不一样的html分别进行css文件打包。因而开始研究extract-text-webpack-plugin插件。
二 插件介绍
打包样式有两种方法,一种是使用style-loader自动将css代码放到生成的style标签中,而且插入到head标签里。另外一种就是使用extract-text-webpack-plugin插件,将样式文件单独打包,打包输出的文件由配置文件中的output属性指定。而后咱们在入口HTML页面写个link标签引入这个打包后的样式文件。
三 插件使用
1 插件安装:css

# for webpack 3 
npm install --save-dev extract-text-webpack-plugin
# for webpack 2 
npm install --save-dev extract-text-webpack-plugin@2.1.2
# for webpack 1 
npm install --save-dev extract-text-webpack-plugin@1.0.1

2 插件使用
在webpack.config.js中引入html

const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader", // 编译后用什么loader来提取css文件
          use: "css-loader" // 指须要什么样的loader去编译文件,这里因为源文件是.css因此选择css-loader
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("styles.css"),
  ]
}

四 APIvue

new ExtractTextPlugin([id: string], filename: string, [options])webpack

  1. id此插件实例的惟一标识。(仅限高级用法;默认状况下,自动生成)
  2. filename结果文件的文件名。可能包含[name],[id]和[contenthash]。
    [name] 块的名称
    [id] 块的标识
    [contenthash] 提取文件内容的哈希值
  3. options
  • allChunks 从全部其余块中提取(默认状况下,它仅从初始块中提取)
  • disable 禁用插件

ExtractTextPlugin.extract([notExtractLoader], loader, [options]
从现有加载器建立提取加载器。web

  1. notExtractLoader(可选)在未提取css时应使用的加载程序(即在其余块中时allChunks: false)
  2. loader 应该用于将资源转换为css导出模块的加载器。
  3. options
    publicPath覆盖publicPath此加载程序的设置。

五 扩展
该实例其实还有一个扩展函数。若是你有多个ExtractTextPlugin,你应该使用它。vue-cli

let ExtractTextPlugin = require('extract-text-webpack-plugin');

// multiple extract instances
let extractCSS = new ExtractTextPlugin('stylesheets/[name].css');
let extractLESS = new ExtractTextPlugin('stylesheets/[name].less');

module.exports = {
  ...
  module: {
    loaders: [
      {test: /\.scss$/i, loader: extractCSS.extract(['css','sass'])},
      {test: /\.less$/i, loader: extractLESS.extract(['css','less'])},
      ...
    ]
  },
  plugins: [
    extractCSS,
    extractLESS
  ]
};
相关文章
相关标签/搜索