webpack 3.X學習之JS壓縮與打包HTML文件

js壓縮

webpack自帶一個插件uglifyjs-webpack-plugin來壓縮js,因此不須要再次安裝,當一切都準備穩當,引入uglifyjs-webpack-plugin模塊:html

const uglify = require('uglifyjs-webpack-plugin');

由於它是一個插件,因此把它放在plugins裏:webpack

plugins:[
    new uglify()
]

這樣就完事了,執行命令webpack,壓縮文件就OK了,通常不會出現問題,(可是我在實際操做中報錯了,uglifyjs-webpack-plugin沒有找到,因此,若是你報錯了,仍是安裝一下吧)git

npm install uglifyjs-webpack-plugin --save-dev

打包HTML文件

首先刪除dist目錄下的全部文件,而後在src文件下建立index.html文件,github

/src/index.htmlweb

<!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>webpack</title>
</head>
<body>
    <div id="title"></div>
</body>
</html>

配置webpack.config.js文件,安裝html-webpack-plugin插件npm

npm install html-webpack-plugin --save-dev

而後引入改插件:緩存

const htmlPlugin =  require('html-webpack-plugin');

在plugins下,加載htmlPlugin插件babel

plugins:[
    new uglify(),
    new htmlPlugin({
        minify:{
            removeAttributeQuotes:true
        },
        hash:true,
        template:'./src/index.html'
    })
]
  • minify:是對html文件進行壓縮, removeAttributeQuotes是去掉屬性的雙引號;
  • hash:爲了開發中js有緩存效果,加入hash,能夠有效避免js緩存;
  • template:須要打包的HTML模板路徑和文件名稱;

參考地址:jsp

相關文章
相關標籤/搜索