Stephan882
Stephan882

Reputation: 133

ReactJS - create chunks automatically with lazy loading

Let's suppose we have three pages and we want to split them into different chunks.That could happen if we manually add /* webpackChunkName: "chunkName" */.

const Home = lazy(() => import(/* webpackChunkName: "HomePage" */ "../../pages/Home"));
const Login = lazy(() => import(/* webpackChunkName: "Login" */ "../../pages/Login"));
const Register = lazy(() => import(/* webpackChunkName: "Register" */ "../../pages/Register"));

Is it possible to make our lives easier and avoid using webpackChunkName all the time?

Upvotes: 1

Views: 1872

Answers (1)

Murli Prajapati
Murli Prajapati

Reputation: 9733

One way is to use [request] placeholder in chunk name comment to dynamically set the chunk name.

You can create a function which will call the import() function and use [request] placeholder to set the dynamic chunk name.

Afterwards, use this function to lazily import components.

Here is one example.

const lazyImport = path => {
  return import(/* webpackChunkName: "[request]" */ `${path}`);
};

const Home = React.lazy(() => lazyImport("../../pages/Home"));
// Chunk name will be pages-Home.chunk.js

Upvotes: 3

Related Questions