Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack and Nodejs isomorphic require with absolute path

GOAL: I am trying to set up a project in nodejs and webpack such that the require function can use the project directory as root, so I can require with absolute path relative to project root in both environments (isomorphic uses i.e. React server+client render).

SITUATION: In webpack you can set the config.resolve.root to make it work, but in nodejs, its best practice not to override/modify the global.require.

PROPOSITION 1: I can make a new global function

global.p_require

so it works in node; however, I cannot find a way to let webpack parse "p_require" into __webpack_require__ without changing the webpack source code.

PROPOSITION 2: I can make a new global variable

global.ROOT_DIR = process.cwd()

so it works in node by

require(ROOT_DIR + <relative path to root>);

however, webpack would recognize this as dynamic require. Is there a way such that webpack would parse ROOT_DIR? I have already tried the Define Plugin, but it seems to load after require is parsed by webpack.

QUESTION

Anyone has a solution or faces the same issue?

like image 768
user2255895 Avatar asked Nov 09 '22 08:11

user2255895


1 Answers

I'm addressing this by letting webpack do more; instead of "node and webpack", it's "webpack: client and server". I have webpack do a build for the client and a build for the server (the latter uses 'node' as its target property in config). It's easy to customize the directories webpack uses to require, so you let it do its work and create a build for node.

When rendering on the server, you just require the compiled server build. If you need to pass some stuff in from the server to the application that webpack built, wire that up in the entry point that you use for the server build -- webpack will build it as a commonJs module, so your entry point can export whatever is the most convenient interface when the server needs to render.

like image 65
Brendan Gannon Avatar answered Nov 14 '22 21:11

Brendan Gannon