webpack 分包js代码

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

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

 

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

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

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

 entry:{ui

    vendor2:['lodash'],this

    gf:'./src/gf.js'spa

    index:'./src/index.js'插件

.....component

  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 />    }); });

相关文章
相关标签/搜索