Unhandled Rejection (ChunkLoadError): Loading chunk 1 failed

时光毁灭记忆、已成空白 提交于 2020-01-05 03:46:24

问题


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.


回答1:


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 :)



来源:https://stackoverflow.com/questions/58256536/unhandled-rejection-chunkloaderror-loading-chunk-1-failed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!