webpack4 四、輸出文件管理

輸出文件管理

html文件需要引用js依賴,如果chunck name是根據[name]、[id]、[hash]、[chunkhash]自動生成的,每次依賴的文件名,可能不一致。使用插件自動生成index文件,併爲我們管理輸出文件

1.index.html的生成

方案一、根據模板自動生成index.html

 plugins: [
        //自動生成index.html文件、、、、、
        new HtmlWebpackPlugin({
            template: 'index.html',//以什麼爲模板文件,在模板文件下新增js依賴
            inject: 'head',//body 將腳本放入head還是body裏
        }),
        //該插件會根據output路徑自動識別輸出文件,並刪除歷史文件,只保留最新構建
        new CleanWebpackPlugin(),

    ],

方案二、配合npm腳本

<%=htmlWebpackPlugin.options.title%>

<% %>js代碼

<%= %>輸出值

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>模板</title>
</head>
<body>
<%=htmlWebpackPlugin.options.title%>
</body>
</html>

2.html文件壓縮

上面插件還可對html文件進行壓縮,

例如去掉空格,,去掉註釋等

3.將js文件與html文件分離開

設置輸出文件路徑,將html與其他文件分隔開

  output: {
        //文件名必須是動態生成的,不然會文件名衝突
        filename: 'js/[name].bundle.js',
        //會根據輸出路徑自動創建新的文件夾,HtmlWebpackPlugin,CleanWebpackPlugin倆插件會根據輸出路徑自動選擇相應文件進行構建
        path: path.resolve(__dirname, 'dist1')
    },

3.完整配置如下

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');


module.exports = {
    entry: {
        app: './src/index.js',
        print: './src/print.js'
    },
    plugins: [
        //自動生成index.html文件、、、、、
        new HtmlWebpackPlugin({
            template: 'index.html',//以什麼爲模板文件,在模板文件下新增js依賴
            inject: 'head',//body將生成的文件
        }),
        //該插件會根據output路徑自動識別輸出文件,並刪除歷史文件,只保留最新構建
        new CleanWebpackPlugin(),

    ],
    output: {
        //文件名必須是動態生成的,不然會文件名衝突
        filename: 'js/[name].bundle.js',
        //會根據輸出路徑自動創建新的文件夾,HtmlWebpackPlugin,CleanWebpackPlugin倆插件會根據輸出路徑自動選擇相應文件進行構建
        path: path.resolve(__dirname, 'dist1')
    },
}
;

4.結果

1.自動生成的文件目錄結構

![image-20190328003737084](/Users/ocean/Library/Application Support/typora-user-images/image-20190328003737084.png)

2.生成的html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>模板</title>
    <script type="text/javascript" src="js/app.bundle.js"></script>
    <script type="text/javascript" src="js/print.bundle.js"></script>
</head>
<body>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章