6

我试图在使用Parcel.js构建时公开一个变量,类似于Webpack DefinePlugin但我还没有找到如何去做。

在开发中,我希望我的 API 主机与我的生产主机不同,所以:

//development:
API_URL="http://localhost:8900/"

//production:
API_URL="/"

目前 Parcel 支持module.hot开关,我可以滥用它,因为热模块重新加载仅在开发中启用,但如果有更好的方法来实现这一点会很好。

我也可以检查 if window.location.hostnameis localhost,但这是一种解决方法。

4

1 回答 1

19

For anyone still seeking an answer to this:

You can use Parcel.js's .env file support (by way of the dotenv package), added in 1.5.0 (2018-01-23).

No additional config needed. Just make your .env files separated by the appropriate NODE_ENV (production, development, etc) and you can access variables via process.env.VARIABLE_NAME. In your case, you could do:

.env.development

API_URL=http://localhost:8900/

.env.production

API_URL=/

And then use it by calling process.env.API_URL (no further imports needed) in your code as needed.

于 2018-02-12T16:07:55.993 回答