簡體   English   中英

在Webpack和React.js中設置代碼拆分

[英]Setting up code splitting in Webpack and React.js

我正在嘗試在我的應用程序中設置代碼拆分/分塊 - 通過路由,使用require.ensure 所以這是我的路線:

<Route path="profile" 
       getComponent={(location, cb) => 
         {require.ensure(
            [], 
            (require) => { cb(null, require('attendee/containers/Profile/').default) }, 
            'attendee')}} />

以下是我的webpack配置中的相關行:

const PATHS = {
  app: path.join(__dirname, '../src'),
  build: path.join(__dirname, '../dist'),
};

const common = {
  entry: [
    PATHS.app,
  ],

  output: {
    path: PATHS.build,
    publicPath: PATHS.build + '/',
    filename: '[name].js',
    chunkFilename: '[name].js',
    sourceMapFilename: '[name].js.map'
  },

  target: 'web',

devtool: 'cheap-module-eval-source-map',
entry: [
  'bootstrap-loader',
  'webpack-hot-middleware/client',
  './src/index',
],
output: {
  publicPath: '/dist/',
},


plugins: [
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: '"development"',
    },
    __DEVELOPMENT__: true,
  }),
  new ExtractTextPlugin('main.css'),
  new webpack.optimize.OccurenceOrderPlugin(),
  new webpack.HotModuleReplacementPlugin(),
  new webpack.NoErrorsPlugin(),
  new webpack.ProvidePlugin({
    jQuery: 'jquery',
  }),
],

當我導航到路徑中的頁面時,我在日志中看到所需的塊已下載。 但是頁面沒有加載。

我在控制台中看到以下堆棧跟蹤:

Uncaught TypeError: Cannot read property 'call' of undefined
t                     @ main.js:10
(anonymous function)  @ main.js:44637
window.webpackJsonp   @ main.js:40
(anonymous function)  @ attendee.js:1

它抱怨的界限是這樣的:

return e[n].call(o.exports, o, o.exports, t)

第二行((匿名函數)@main.js:44637)基本上是這樣的:

require('attendee/containers/Profile/').default

注意,如果我執行console.log(require('./attendee/containers/Profile/').default) ,我會得到一個函數作為輸出,所以我不確定為什么它是未定義的。 當然,當我這樣做時,代碼可以工作,但是不再有任何分塊。

所以我做一些錯誤的require 知道它是什么?

順便說一下,我在這個項目中使用哈希歷史 - 這可能是罪魁禍首嗎?

更新:

還嘗試了在這個答案中的bundle-loader。 結果相同。

你快到了! 試試這個:你需要在require.ensure的第一個參數中提前特定模塊依賴項數組而不是[]顯式設置為['attendee/containers/Profile']

(location, cb) => {
  require.ensure(['attendee/containers/Profile'], (require) => {
    cb(null, require('attendee/containers/Profile').default) 
  }) 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM