简体   繁体   中英

Unhandled Rejection (ChunkLoadError): Loading chunk 1 failed

I am basically trying to do a poc on extracting the some part of my main application into a separate package.A Sample separate package I have built it in my git repo myapp-poc-ui .

Now I am trying to access this in my main application.
package.json:

 "dependencies": {
    "myapp-poc-ui": "git+https://github.com/prabhatmishra33/myapp-poc-ui#master",
    "react": "^16.10.1",
    "react-dom": "^16.10.1",
    "react-scripts": "3.2.0"
  },

I am accessing the exported module in my main app by:

import React from 'react';
import './App.css';
import { HelloWorld } from "myapp-poc-ui";
import { LazyComponent } from "myapp-poc-ui";

function App() {
  return (
    <div>
      <HelloWorld />
      <LazyComponent />
    </div>
  );
}

export default App;

Issue: I am getting an issue on my browser

Uncaught SyntaxError: Unexpected token '<'
Uncaught (in promise) ChunkLoadError: Loading chunk 1 failed.

Hello World gets loaded properly but this issue comes while loading the LazyComponent .

I am guessing there is something wrong in webpack config file publicPath property for myapp-poc-ui

Any design change suggestion is also welcome.

Thanks in advance.

So here is the problem, whenever myapp-poc-ui builds, it creates

  1. Main entry file
  2. Rest all are chunk files

The chunk file doesn't gets loaded automatically in build unless the app renders. Once app renders, it calls for the chunk file to load over the network. You client app needs to have that chunk file in public or dist folder which is server on localhost, it cannot automatically get the chunk file unless we copy it from node module to the public.

Your module has created the chunk but the client app doesn't automatically loads/copies the file while creating the client's build, and if we make the file calling as part of myapp-poc-ui then it defeats the purpose of using Lazy-Loading. So one way to do this is to copy the node file into your served folder or build folder.

 // i am using create-react-app as client and used react-app-rewired to // overide cra webpack in config-overrides.js const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = function override(config, env) { //do stuff with the webpack config... config.plugins = [ new CopyWebpackPlugin([ { context: 'node_modules/myapp-poc-ui/dist/', from: '*', to: '[name].[ext]', toType: 'template', }, ]), ...config.plugins, ]; console.log(config) return config; }

Happy Coding:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM