本文主要記載的是WebPlugin插件的用法
主要實現的功能:
1:壓縮js通過UglifyJsPlugin
2:使用WebPlugin根據模板自動生成頁面
3:使用extract-text-webpack-plugin 將css抽取爲單獨的css文件,導入所需頁面中
先看目錄結構
下面爲webpack.config.js的配置文件
const path = require('path');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin'); //壓縮js
const ExtractTextPlugin = require('extract-text-webpack-plugin'); //抽取css爲單獨的文件
const DefinePlugin = require('webpack/lib/DefinePlugin'); //定義程序環境
const { WebPlugin } = require('web-webpack-plugin'); //根據模板自動生成html頁面
module.exports = {
entry: {
app: './main.js'// Chunk app 的 JS 執行入口文件 ,chunk名稱爲app
},
output: {
filename: '[name]_[chunkhash:8].js',// 給輸出的文件名稱加上 hash 值
path: path.resolve(__dirname, './dist'), //輸出文件路徑 等於 cd __dirname, cd ./dist pwd
},
module: {
rules: [
{
test: /\.js$/,
use: ['babel-loader'],
// 排除 node_modules 目錄下的文件,node_modules 目錄下的文件都是採用的 ES5 語法,沒必要再通過 Babel 去轉換
exclude: path.resolve(__dirname, 'node_modules'),
},
{
test: /\.css/,// 增加對 CSS 文件的支持
// 提取出 Chunk 中的 CSS 代碼到單獨的文件中
use: ExtractTextPlugin.extract({
use: ['css-loader?minimize'] // 壓縮 CSS 代碼
}),
},
]
},
plugins: [
// 使用本文的主角 WebPlugin,一個 WebPlugin 對應一個 HTML 文件
new WebPlugin({
template: './template.html', // HTML 模版文件所在的文件路徑
filename: 'index.html' // 輸出的 HTML 的文件名稱
}),
new ExtractTextPlugin({
//[name]對應入口文件的名字app(chunk名) 模板中書寫app?_inline.css
filename: `[name]_[contenthash:8].css`,// 給輸出的 CSS 文件名稱加上 hash 值
}),
new DefinePlugin({
// 定義 NODE_ENV 環境變量爲 production 去除 react 代碼中的開發時才需要的部分
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
// 壓縮輸出的 JS 代碼
new UglifyJsPlugin({
// 最緊湊的輸出
beautify: false,
// 刪除所有的註釋
comments: false,
compress: {
// 在UglifyJs刪除沒有用到的代碼時不輸出警告
warnings: false,
// 刪除所有的 `console` 語句,可以兼容ie瀏覽器
drop_console: true,
// 內嵌定義了但是只用到一次的變量
collapse_vars: true,
// 提取出出現多次但是沒有定義成變量去引用的靜態值
reduce_vars: true,
}
}),
],
};
template.html模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!--注入 Chunk app中的css -->
<!-- app是chunk名,_inline表示代碼需內嵌到該位置,相同參數還有
_dist:生產環境下才引入該資源, _dev:開發環境下才引入該資源 _ie:IE瀏覽器下
才引入該資源。可搭配使用app?_inline&_dist
-->
<link rel="stylesheet" href="app?_inline">
<script src="./google_analytics.js?_inline"></script>
<script src="https://dive-into-webpack.disqus.com/embed.js" async></script>
</head>
<body>
<div id="app"></div>
<!--導入 Chunk app 中的 JS-->
<script src="app"></script>
<!--Disqus 評論容器-->
<div id="disqus_thread"></div>
</body>
</html>
入口文件代碼:
import React, { Component } from 'react';
import { render } from 'react-dom';
//一個入口,那麼所有文件都從此處讀取
import './main.css';
class Button extends Component {
render() {
return <h1>Hello,Webpack</h1>
}
}
render(<Button/>, window.document.getElementById('app'));
這樣一執行就會生成如下文件,其中index.html就是根據template.html生成的,並且相應的文件也會被自動插入