美文网首页
代码分割

代码分割

作者: visitor009 | 来源:发表于2018-09-22 20:21 被阅读0次

    代码分割:当两个文件同时引用同一个模块时时,将其抽取出来
    官方例子

    // webpack.config.js
    const path = require('path');
    const HTMLWebpackPlugin = require('html-webpack-plugin');
    const webpack = require('webpack');
    
    module.exports = {
        entry: {
            index: './src/index.js',
            another: './src/another-module.js'
        },
        plugins: [
            new HTMLWebpackPlugin({
                title: 'Code Splitting'
            })
        ],
        output: {
            filename: '[name].bundle.js',
            path: path.resolve(__dirname, 'dist')
        },
        optimization: {
            splitChunks: {
              chunks: 'async',
              minSize: 30000,
              maxSize: 0,
              minChunks: 1,
              maxAsyncRequests: 5,
              maxInitialRequests: 3,
              automaticNameDelimiter: '~',
              name: true,
              cacheGroups: {
                common: {
                  name: 'common',
                  chunks: 'initial',
                  priority: 2,
                  minChunks: 2,
                },
              }
            }
          }
    };
    // index.js
    import _ from 'lodash';
    
    console.log(
      _.join(['index', 'module', 'loaded!'], ' ')
    );
    // another-module.js
    import _ from 'lodash';
    
    console.log(
      _.join(['Another', 'module', 'loaded!'], ' ')
    );
    
    // 最后生成3个文件
     index.bundle.js
    another-module.bundle.js 
    common.bundle.js
    

    懒加载(动态加载):通过某个条件动态加载js文件,而不是当前文件加载时导入,注意,html文件要和js在同一个目录webpack官方例子

    // webpack.config.js
    const path = require('path');
    const HTMLWebpackPlugin = require('html-webpack-plugin');
    const webpack = require('webpack');
    
    module.exports = {
        entry: {
            index: './src/index.js',
        },
        output: {
            filename: '[name].bundle.js',
            path: path.resolve(__dirname, 'dist')
        },
        plugins: [
            new HTMLWebpackPlugin({
              title: 'Code Splitting'
            })
        ]
    };
    // index.js
    function Button() {
        let btn = document.createElement('button');
        btn.innerHTML = 'load';
        btn.onclick = function() {
            import('./print').then(module=>{
                let print = module.default;
                print();
            })
        }
        return btn;
    }
    document.body.appendChild(Button());
    // print.js
    console.log('The print.js module has loaded! See the network tab in dev tools...');
    
    export default () => {
      console.log('Button Clicked: Here\'s "some text"!');
    }
    

    相关文章

      网友评论

          本文标题:代码分割

          本文链接:https://www.haomeiwen.com/subject/fuexoftx.html