上一節(jié)我們介紹了如何使用loaders包券,將style.css文件動態(tài)寫入到j(luò)s文件中,在文章末尾株旷,需要解決這樣一個問題:
css是通過javascript動態(tài)創(chuàng)建標(biāo)簽來寫入的再登,這就意味著樣式代碼已經(jīng)編譯在index.js文件里。但是實際業(yè)務(wù)中晾剖,可能并不希望這么做锉矢,因為隨著項目的增大和樣式的增多,js的體積會越來越大齿尽,而且不能做緩存沽损。這是就需要用到webpack最后一個重要的概念——插件(plugins)。
webpack的插件功能很強大而且可以定制循头,我們使用一個extract-text-webpack-plugin的插件將散落在各地的css提取出來绵估,并生成一個index.css文件,最終在index.html中通過<link>的形式引入它卡骂。
安裝extract-text-webpack-plugin:
npm install?extract-text-webpack-plugin --save-dev
然后在webpack.config.js中引入插件国裳,并修改rules屬性、添加plugins熟悉:
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var config = {
? ? entry: {
? ? ? ? main: './index'
? ? },
? ? output: {
? ? ? ? path: path.join(__dirname, './dist'),
? ? ? ? publicPath: '/dist/',
? ? ? ? filename: 'index.js'
? ? },
? ? module: {
? ? ? ? rules: [
? ? ? ? ? ? {
? ? ? ? ? ? ? ? test: /\.css$/,
? ? ? ? ? ? ? ? use: ExtractTextPlugin.extract({
? ? ? ? ? ? ? ? ? ? use: 'css-loader',
? ? ? ? ? ? ? ? ? ? fallback: 'style-loader'
? ? ? ? ? ? ? ? })
? ? ? ? ? ? }
? ? ? ? ]
? ? },
? ? plugins: [
? ? ? ? //重命名提取后的css文件
? ? ? ? new ExtractTextPlugin('index.css')
? ? ]
};
module.exports = config;
在根目錄新建other.css全跨,代碼如下:
#app {
? ? line-height: 30px;
}
index.js引入other.css躏救,代碼如下:
import './style.css';
// var styles = require('./style.css');
import './other.css';
setTimeout(() => {
? ? document.getElementById('app').innerHTML = 'Hello Webpack And Vue!';
}, 5000);
在index.html引入聲明的index.css文件(與webpack.config.js文件plugins聲明的文件名一致),代碼如下:
//其他代碼省略
<link rel="stylesheet" href="dist/index.css">
重新啟動,發(fā)現(xiàn)字體顏色盒使、大小崩掘、行間距發(fā)生了變化,打開控制臺發(fā)現(xiàn)<style>標(biāo)簽沒有了少办,打開index.css文件苞慢,代碼如下:
發(fā)現(xiàn)已經(jīng)將style.css和other.css的內(nèi)容合并至index.css中。
至此英妓,我們完成了一個簡單的plugins使用示例挽放。
完整代碼github地址:https://github.com/zhiyuanMain/zhihu-daily