版本
webpack@4.46.0
react@16.5.2
react-router@5.2.0
babel-loader@7.1.5

因为版本限制原因,无法用react.lazy实现路由懒加载。为了减小首次加载的文件大小,实现动态加载,使用webpack的动态加载能力。网上找了一些方法,走了不少弯路。以下提供特定版本范围的可行方案,供需要的同学参考。
1.webpack 配置,用babel-plugin-syntax-dynamic-import(v6.18.0)
use: {

loader: 'babel-loader',
options: {
  babelrc: false,
  cacheDirectory: false,
  plugins: [
    ['syntax-dynamic-import'] //动态加载插件
  ],
  presets: [
    require.resolve('babel-preset-react-native', '@babel/preset-env')
  ]
}

}
module.exports = {
output: {

filename: '[name].[hash:8].js',
path: path.resolve(webDirectory, 'dist'),
globalObject: 'this',
publicPath: '',
chunkFilename: '[name].[hash:8].js'

},
optimization: {

splitChunks: {
  chunks: 'all',
  minSize: 20000,
  maxSize: 0,
  minChunks: 1,
  maxAsyncRequests: 30,
  maxInitialRequests: 30,
  automaticNameDelimiter: '~',
  enforceSizeThreshold: 50000,
  cacheGroups: {
    vendors: {
      test: /[\\/]node_modules[\\/]/,
      priority: -10,
      name: 'vendors',
      reuseExistingChunk: true
    },
    default: {
      minChunks: 2,
      priority: -20,
      reuseExistingChunk: true
    }
  }
},

}
}

2.router.js
引入@loadable/componen,把路由传入loadable函数
import loadable from '@loadable/component';
const A = loadable(() => import('../A'));


xieyanmei
49 声望4 粉丝