zoukankan      html  css  js  c++  java
  • webpack笔记三 管理输出

    webpack笔记三 管理输出

    增加src/print.js

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

    src/index.js中导入它:

    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中增加一个入口:

    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.html

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

    打包后可以看到效果:

    使用 HtmlWebpackPlugin 插件

    经过以上实践,我们发现每次修改输出文件名,都得手动修改dist/index.html文件,如果给输出文件名增加了hash值维护起来更是麻烦。懒是进步的动力:

    安装 HtmlWebpackPlugin 插件:

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

    webpack.config.js

    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,替换掉之前的文件。

    HtmlWebpackPlugin插件
    html-webpack-template提供默认模板之外,还提供了一些额外的功能。

    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源码

  • 相关阅读:
    ASCII对照表
    Python学习记录-3-简明Python教程-数据结构
    Python学习记录-2
    Python新手容易遇到的问题
    python学习问题之-编码
    同步与异步的概念(转自http://blog.chinaunix.net/uid-21411227-id-1826898.html)
    Objective-c学习三
    挺有意思的人体时钟代码(转自http://ziren.org/tools/hone-hone-clock.html)
    int ,long , long long类型的范围
    css3选择器使用例子
  • 原文地址:https://www.cnblogs.com/jehorn/p/10763102.html
Copyright © 2011-2022 走看看