react按需加載(getComponent優美寫法),並指定輸出模塊名稱解決緩存(getComponent與chunkFilename)


react配合webpack進行按需加載的方法很簡單,Route的component改為getComponent,組件用require.ensure的方式獲取,並在webpack中配置chunkFilename。
const chooseProducts = (location, cb) => { require.ensure([], require => { cb(null, require('../Component/chooseProducts').default) },'chooseProducts') } const helpCenter = (location, cb) => { require.ensure([], require => { cb(null, require('../Component/helpCenter').default) },'helpCenter') } const saleRecord = (location, cb) => { require.ensure([], require => { cb(null, require('../Component/saleRecord').default) },'saleRecord') } const RouteConfig = ( <Router history={history}> <Route path="/" component={Roots}> <IndexRoute component={index} />//首頁 <Route path="index" component={index} /> <Route path="helpCenter" getComponent={helpCenter} />//幫助中心 <Route path="saleRecord" getComponent={saleRecord} />//銷售記錄 <Redirect from='*' to='/' /> </Route> </Router> );


舊寫法

<Route path="movieSearch/:keyWord"
  getComponent={
    (nextState, callback)=> {
      require.ensure([], (require)=> {
      callback(null, require("../containers/MovieSearchContainer.js").default)
    }, "movieSearch")
   }
  }
/>

 
require-ensure 
    • 說明: require.ensure在需要的時候才下載依賴的模塊,當參數指定的模塊都下載下來了(下載下來的模塊還沒執行),便執行參數指定的回調函數。require.ensure會創建一個chunk,且可以指定該chunk的名稱,如果這個chunk名已經存在了,則將本次依賴的模塊合並到已經存在的chunk中,最后這個chunk在webpack構建的時候會單獨生成一個文件。
    • 語法:require.ensure(dependencies: String[], callback: function([require]), [chunkName: String])
      • dependencies: 依賴的模塊數組
      • callback: 回調函數,該函數調用時會傳一個require參數
      • chunkName: 模塊名,用於構建時生成文件時命名使用
    • 注意點:requi.ensure的模塊只會被下載下來,不會被執行,只有在回調函數使用require(模塊名)后,這個模塊才會被執行。
 

output: {
  path: path.resolve(__dirname, 'dist'),
  // filename應該比較好理解,就是對應於entry里面生成出來的文件名
  filename: 'bundle.js',
  // 為了做代碼的異步加載,所有文件都以/代替根目錄轉換,即輸入/就會自動轉為根目錄
  // “publicPath”項則被許多Webpack的插件用於在生產模式下更新內嵌到css、html文件里的url值,解決Link標簽里的to用絕對路徑問題
  publicPath:'/',
  // chunkname我的理解是未被列在entry中,卻又需要被打包出來的文件命名配置。
  // 在按需加載(異步)模塊的時候,CommonJS的方式異步加載模塊:require.ensure() API,

  //異步加載的模塊是要以文件形式加載哦,所以這時生成的文件名是以chunkname配置的,生成出的文件名,同時解決緩存問題
  chunkFilename: '[name]_[chunkhash:8]_chunk.js'
},

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM