Code splitting not working with parcel in react

206 views Asked by At

I have this component which is from parcel's documentation. It said it should work by default.

import React from 'react';

const Router = () => {
 ...
  const ComponentToRender = React.lazy(() => import(`./Pages/${variableCompoentName}/index.js`));
  return (
    <React.Suspense fallback={<div>Loading...</div>}>
      <ComponentToRender />
    </React.Suspense>
  );
};

export default Router;

But I get an error in the browser saying:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

2src.7ed060e2.js:1362 Uncaught TypeError: Failed to fetch dynamically imported module: http://localhost:1234/Pages/Home/index.js

What is the way around this? and what am I doing wrong?

here is my package.json

  "dependencies": {
    "@babel/core": "^7.12.3",
    "@babel/preset-env": "^7.12.1",
    "@babel/preset-react": "^7.12.5",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "parcel-bundler": "^1.12.5",
    "react": "^16.9.0 || ^17.0.0 || ^18",
    "react-dom": "^18.2.0",
     ...
  },
  "scripts": {
    "start": "parcel public/index.html",
    "build": "parcel build public/index.html",
  }

Update 1 December 2023

Turns out I get the error because I am using a variable(variableCompoentName) inside import(./Pages/${variableCompoentName}/index.js)). because the names were generated at runtime, so they are never compiled.

Now my question is how do I ensure that they always get compiled? How do I go around this issue?

1

There are 1 answers

0
Damian Chudobiński On

As guerric-p suggest in Why does the server return MIME type of 'text/html' when I import React?

That could be cause you are need also ReactDOM

import React from 'react';
import ReactDOM from 'react-dom';

I'm not used to react but when u use file .js im think you should qoute your components / html

Instead of

return (
    <React.Suspense fallback={<div>Loading...</div>}>
      <ComponentToRender />
    </React.Suspense>
  );

Do something like

return "<React.Suspense fallback={<div>Loading...</div>}><ComponentToRender /></React.Suspense>";

Or

return (
    <React.Suspense fallback={"<div>Loading...</div>"}>
      <ComponentToRender />
    </React.Suspense>
  );

And make sure on local enviroment like visual studio to run in terminal npm run start