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

相關文章
相關標籤/搜索