简体   繁体   English

Webpack和Nodejs同构需要绝对路径

[英]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 ie React server+client render). 目标 :我正在尝试在nodejswebpack中设置一个项目, 以便 require函数可以以root身份使用项目目录,因此我可以在两个环境中使用相对于项目根的绝对路径同构使用即React服务器+客户端呈现)。

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. 情况 :在webpack中你可以设置config.resolve.root使它工作,但在nodejs中,最好不要覆盖/修改global.require。

PROPOSITION 1 : I can make a new global function 提议1 :我可以创建一个新的全局功能

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. 但是,我无法找到一种方法让webpack将“p_require”解析为__webpack_require__而不更改webpack源代码。

PROPOSITION 2 : I can make a new global variable 提案2 :我可以创建一个新的全局变量

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 . 但是,webpack会认为这是动态需求 Is there a way such that webpack would parse ROOT_DIR? 有没有办法让webpack解析ROOT_DIR? I have already tried the Define Plugin , but it seems to load after require is parsed by webpack. 我已经尝试过Define Plugin ,但似乎在webpack解析require之后加载。

QUESTION

Anyone has a solution or faces the same issue? 任何人都有解决方案或面临同样的问题?

I'm addressing this by letting webpack do more; 我正在解决这个问题,让webpack做得更多; instead of "node and webpack", it's "webpack: client and server". 而不是“节点和webpack”,它是“webpack:客户端和服务器”。 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). 我有webpack为客户端做一个构建和服务器的构建(后者在config中使用'node'作为它的目标属性)。 It's easy to customize the directories webpack uses to require, so you let it do its work and create a build for node. 定制webpack使用的目录很容易,因此您可以让它完成工作并为节点创建构建。

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. 如果您需要将一些内容从服务器传递到webpack构建的应用程序,请将其连接到用于服务器构建的入口点 - webpack将其构建为commonJs模块,因此您的入口点可以导出任何内容是服务器需要渲染时最方便的界面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM