延迟加载React Uncaught SyntaxError:意外令牌<

时间:2018-11-12 19:08:27

标签: reactjs webpack lazy-loading code-splitting

我正在尝试在我的react应用程序中实现延迟加载和块拆分。到目前为止,一切都工作正常,并且确实没有出现任何谷歌无法解决的问题,但这是我的主意。请在下面找到我的babel和webpack配置设置。

.babelrc

{
  "plugins": [
  "@babel/plugin-syntax-dynamic-import",
  "@babel/plugin-transform-member-expression-literals",
  "@babel/plugin-transform-property-literals",
  "@babel/plugin-proposal-object-rest-spread",
  "@babel/plugin-proposal-class-properties",
  "@babel/plugin-transform-runtime",
  "@babel/plugin-transform-regenerator"
 ],
 "presets": [
 [
  "@babel/preset-env",
   {
     "useBuiltIns": "usage"
   }
  ],
  "@babel/preset-react"
 ],
 "env": {
  "karma": {
   "plugins": [
    [
      "istanbul",
      {
        "exclude": [
          "tests/*.test.js"
        ]
      }
     ]
   ]
  }
 }
}

weback.config.js

`
 const developmentConfig = merge([
    {
      output: {
      chunkFilename: '[name].[chunkhash:4].js',
      filename: '[name].[chunkhash:4].js',
      path: PATHS.build,
    },
    optimization: {
      splitChunks: {
        cacheGroups: {
          commons: {
           test: NodeRegex,
           name: 'vendor',
           chunks: 'initial',
           minChunks: 2,
         },
       },
     },
    },
  },
  parts.loadCSS(),
  parts.loadImages(),
  parts.generateSourceMaps({ type: 'cheap-module-eval-source-map' }),
  parts.clean(PATHS.build), // deletes old dist folder
]);`

 module.exports = (mode) => {
  if (mode === 'production') {
   return merge(commonConfig, productionConfig, { mode });
  }
  return merge(commonConfig, developmentConfig, { mode });
 };

1 个答案:

答案 0 :(得分:0)

我终于解决了这个问题。问题出在我的模板中。我已经设定了这样的公开道路:

<% var reactClentPath = '/react-client/dist'; %>
<script src="<%= reactClentPath %>/<%= htmlWebpackPlugin.files.chunks[key].entry %>" type="text/javascript"></script>

我要做的就是把它拿出来,并允许在我的webpack-config.js中设置的公共路径来处理这个问题。     <script src="<%= htmlWebpackPlugin.files.chunks[key].entry %>"