简体   繁体   中英

Common boilerplate for multiple entry points in Webpack

In Webpack (4) are there ways to pass export(s) of a given entry file into a helper module, which itself acts as entry? Basically a way to "wrap" entry points.

Now, I know I can easily use CommonChunks to import into an entry, but what I trying to do is export from the entry for another module to actually do something in its place. Here's why.

I have a react application which I'm using Webpack to build. I am porting from a NEXT.js stack which, for my purposes, is a source of overhead. One feature I want to keep though, is putting routes in a pages/ folder where I export default Component in each page, rendering automagically. This would be very nice behavior to have for a Webpack project.

Right now, I get my directory-based-multiple-entry roughly like this.

/* webpack.config.js */

const pages = {};

for(let route of fs.readdirSync('./pages')){
    pages[route] = path.resolve('./pages', route);
}

module.exports = {
    entry: pages,
    /* ... */
}

It works; but I do need to require and setup ReactDOM.render for every entry. Alone this is not a big deal, but when getting into HMR (hot-reloading) and other things, it adds a lot of redundancy. It also makes it harder to keep my code dev/production agnostic.

What I'd like to do is this. Have one module somewhere in my project which does the actual rendering of my pages, something like:

/* init.js */

const MyEntryPoint = require("🤷‍♂️").default;

const intoContainer = 
    document.body.appendChild(document.createElement("div"))

ReactDOM.render(MyEntryPoint, intoContainer);

with my multiple entry pages looking like

/* pages/login/index.js */

export default () => (
    <div>Welcome to the login page!</div>
)

I know there is a way to pass an array for given entries, but to my understanding they are concatenated and cannot import one another. My only other theory is to export each page as a library and manually include bootstrap code as a script-tag.

Is there any better way to do this?

I did actually figure this out at some point. Ended up rolling my own solution called
Webpack Intermediate Entry .

What it does is load a given insert file, specified in IntermediateEntryPlugin .

You can install and import this plugin via NPM as webpack-intermediate-entry .

It then replaces all entries with that file, and replacing "__webpack_entry__" import, with each in-turn.

Hopefully it helps!

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