learner
learner

Reputation: 4818

Multiple modules for multiple entry points in webpack config for reactjs app

In case of multiple entry points, this is the example I got:

module.exports = {
    entry: {
        user1: path.join(__dirname, './client/app1.js'),
        user2: path.join(__dirname, './client/app2.js'),
        user3: path.join(__dirname, './client/app3.js')
    },
    output: {
        path: path.join(__dirname, './static/bundle/'),
        filename: '[name].js'
    },
    ...
}

But, I am confused about the term entry. Does it mean the entry url? What if user visits to root and then visits another page?

For example, suppose I have one site example.com and two other pages example.com/register and example.com/contact. Now I want to get common files for example.com and load only register module code in example.com/register and contact module code in example.com/contact. The entry point is same, example.com. Will above solution work in this scenario?

Upvotes: 3

Views: 11319

Answers (1)

Michael Peyper
Michael Peyper

Reputation: 6944

But, I am confused about the term entry. Does it mean the entry url?

No. It is the entry for webpack to start bundling. If you have multiple entries in your webpack config, then there will be multiple output bundles. This is why you output uses a [name].js in the filename.

It is up to you to make sure the correct bundle(s) are available to any particular page that is loaded.


Answering question in comment:

If I understand what you are trying to do, I believe you can use CommonsChunkPlugin to construct a common bundle and an entry for each page.

So your webpack config might look something like

module.exports = {
    entry: {
        index: path.join(__dirname, './src/index.js'),
        register: path.join(__dirname, './src/register.js'),
        contact: path.join(__dirname, './src/contact.js')
    },
    output: {
        path: path.join(__dirname, './static/bundle/'),
        filename: '[name].js'
    },
    plugins: [
        new CommonsChunkPlugin("commons.js")
    ]
    ...
}

Then your index page would be something like

<html>
    <head></head>
    <body>
        ...
        <script src="static/bundle/commons.js"></script>
        <script src="static/bundle/index.js"></script>
    </body>
</html>

And the register page would be something like

<html>
    <head></head>
    <body>
        ...
        <script src="static/bundle/commons.js"></script>
        <script src="static/bundle/register.js"></script>
    </body>
</html>

And the contact page would be something like

<html>
    <head></head>
    <body>
        ...
        <script src="static/bundle/commons.js"></script>
        <script src="static/bundle/contact.js"></script>
    </body>
</html>

Upvotes: 6

Related Questions