zoukankan      html  css  js  c++  java
  • webpack 分包js代码

    在js代码中不断使用import,会导致2个js文件都将一个库(如lodash)加载到了各自的文件中。导致文件过大。例如:

    a.js中使用了import _ from "lodash";b.js中也使用了import _ from "lodash";那么打包完成后,a.js和b.js代码中都包含了lodash代码,a和b都很大很大。这明显不合理。

    (方案1):不适用任何插件。

    直接将库(如lodash等)作为一个entry,然后打包的时候将这些库生成的代码直接嵌入到html中,而不是嵌入到a.js和b.js中。具体代码如下:

    我使用了第三方库lodash和自己写的函数库gf.js。这个时候在代码中就不要import了。

     entry:{

        vendor2:['lodash'],

        gf:'./src/gf.js'

        index:'./src/index.js'

    .....

      plugins:[

          new HtmlWebpackPlugin({

             title:"HM",

             filename:"index.html",

             template:"tpl.html",

             inject:"body",

             chunks:['vendors','gf','index']//

           }),

    ....

     总结:其实就是类似于传统的js编写方法,写完后将公共库插入到html中,不影响index.js。这种方法显然不好,而且编程的时候还有一些莫名其妙的问题,比如变量访问不到。

    (方案1):require.ensure 按需加载

    模块中,最好设定好。以下两种方法都可以。

    module.exports = Banner;//模块名称为Banner,Footer,Header

    //分割代码,异步加载
    //appoach 1:
    require.ensure([], (require) => {
        const Footer = require('../component/footer');
        const Header = require('../component/header');
        this.setState({
            footer: <Footer />,
            header: <Header bselectedIndex={0} />
        });
    });

    //appoach 2:
    import('../component/banner').then(Banner => {
        console.log(Banner);
        console.log(Banner.default);
        this.setState({
            banner: <Banner.default />
        });
    });

  • 相关阅读:
    pgrep 查询进程的工具
    shell脚本中>/dev/null的含义
    一条命令批量替换多个文件中字符串
    Centos 6.4上面用Shell脚本一键安装vsftpd
    centos 卸载vsftpd方法
    Centos 6.4上面用Shell脚本一键安装mysql 5.6.15
    SHELL学习笔记----IF条件判断,判断条件
    CentOS挂载新硬盘
    Linux fdisk 命令
    Linux df 命令
  • 原文地址:https://www.cnblogs.com/dongfangchun/p/9300630.html
Copyright © 2011-2022 走看看