webpack筆記三 管理輸出

webpack筆記三 管理輸出

增長src/print.jsjavascript

export default function printMe() {
    console.log('I get called from print.js!');
}

src/index.js中導入它:html

import _ from 'lodash';
import printMe from './print';

function component() {
    let element = document.createElement('div');
    let btn = document.createElement('button');

    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

    btn.innerHTML = 'Click here, then watch the console!';
    btn.onclick = printMe;

    element.appendChild(btn);

    return element;
}

document.body.appendChild(component());

webpack.config.js中增長一個入口:java

const path = require('path');

module.exports = {
    entry: {
        app: './src/index.js',
        print: './src/print.js'
    },
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
};

到這裏,還須要手動修改dist/index.htmlwebpack

<html lang="en">
...
<body>
    <script src="app.bundle.js"></script>
</body>
</html>

打包後能夠看到效果:git

使用 HtmlWebpackPlugin 插件

通過以上實踐,咱們發現每次修改輸出文件名,都得手動修改dist/index.html文件,若是給輸出文件名增長了hash值維護起來更是麻煩。懶是進步的動力:github

安裝 HtmlWebpackPlugin 插件:web

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

webpack.config.jsnpm

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

module.exports = {
    entry: {
        app: './src/index.js',
        print: './src/print.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: '管理輸出'
        })
    ],
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
};

HtmlWebpackPlugin會生成一個index.html,替換掉以前的文件。json

HtmlWebpackPlugin插件
html-webpack-template提供默認模板以外,還提供了一些額外的功能。bash

CleanWebpackPlugin 清理/dist文件夾

npm install --save-dev clean-webpack-plugin

webpack.config.js

...
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
    ...
    plugins: [
        ...
        new CleanWebpackPlugin()
    ],
    ...
};

manifest

webpack經過manifest追蹤全部模塊到輸出bundle之間的映射。
經過WebpackManifestPlugin能夠將manifest數據提取爲一個json文件。

The end... Last updated by: Jehorn, April 24, 2019, 4:22 PM
demo源碼

相關文章
相關標籤/搜索