【问题标题】:Conditional require in express?有条件的要求快递?
【发布时间】:2018-10-25 22:33:28
【问题描述】:

我正在开发中使用reload 包。

它保存在devDependancies 下的package.json

在我的app.js 我有:

if (process.env.NODE_ENV !== 'production') {
    reload(server, app)
}

Heroku 在构建后删除了devDependancies 下的所有包,而我的import reload from 'reload' 则抛出错误。我正在使用 babel 在生产环境中构建它。

Heroku 日志:

Error: Cannot find module 'reload'
2018-05-16T01:00:46.213772+00:00 app[web.1]:     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:571:15)
2018-05-16T01:00:46.213773+00:00 app[web.1]:     at Function.Module._load (internal/modules/cjs/loader.js:497:25)
2018-05-16T01:00:46.213776+00:00 app[web.1]:     at Module.require (internal/modules/cjs/loader.js:626:17)

我知道我可以 skip the "pruning" part,但我更愿意在生产中剥离 reload 模块的加载。

我如何有条件地导入或需要一个包?

【问题讨论】:

    标签: node.js express heroku production-environment


    【解决方案1】:

    一般规则是将您的导入放在顶部,但您不必这样做

    if (process.env.NODE_ENV !== 'production') {
        require('reload')(server, app)
    }
    

    应该可以。

    【讨论】:

    • 在顶部使用条件require 时出现“性能损失”?我在两种模式下都使用const x= require('x')
    猜你喜欢
    • 2011-07-05
    • 2012-12-23
    • 1970-01-01
    • 2017-07-11
    • 2015-09-23
    • 2011-07-17
    • 2019-07-05
    • 1970-01-01
    • 2013-08-04
    相关资源
    最近更新 更多