在节点中如何仅在开发构建期间导出功能以进行测试?
In node how to export functions only during dev build for testing?
我创建了一个节点应用程序,并在一个文件中包含了一些函数。我想对它们进行测试,所以我正在导出函数,但这是一个安全问题,所以无论如何我只在开发时间导出它吗?
这是我的资料:
async function AuthenticateHandler(req: Restify.Request, res: Restify.Response, next) { ... });
function shutdownServer() { ... }
module.exports = {
AuthenticateHandler,
shutdownServer
};
为了构建,我目前使用 Gulp 文件并提供参数来告诉它它在哪个环境中构建:
task("Build", series(CopyConfig));
function CopyConfig(cb){
if(arg.env == "dev"){
return src(['config.dev.json'])
.pipe(rename("config.json"))
.pipe(dest('./dist'));
} else if(arg.env == "prod"){
return src(['config.prod.json'])
.pipe(rename("config.json"))
.pipe(dest('./dist'));
}else if(arg.env == "local"){
return src(['config.local.json'])
.pipe(rename("config.json"))
.pipe(dest('./dist'));
}
};
如何只在开发和本地环境中导出?
尝试使用当前环境的值设置环境变量,然后将 'module.exports' 放入 if 块中。
if(process.env['ENV'] === 'dev'){
module.exports = {};
}
一种选择是使用环境变量,它可以在任何文件中访问。您可以将脚本添加到 package.json
文件:
"scripts": {
"build:dev": "NODE_ENV='development' gulp"
}
然后,在你的导出文件中,像这样:
async function AuthenticateHandler(req: Restify.Request, res: Restify.Response, next) { ... });
function shutdownServer() { ... }
module.exports.shutdownServer = shutdownServer;
// conditionally export a function
if (process.env.NODE_ENV === 'development') {
module.exports.AuthenticateHandler = AuthenticateHandler;
}
我创建了一个节点应用程序,并在一个文件中包含了一些函数。我想对它们进行测试,所以我正在导出函数,但这是一个安全问题,所以无论如何我只在开发时间导出它吗?
这是我的资料:
async function AuthenticateHandler(req: Restify.Request, res: Restify.Response, next) { ... });
function shutdownServer() { ... }
module.exports = {
AuthenticateHandler,
shutdownServer
};
为了构建,我目前使用 Gulp 文件并提供参数来告诉它它在哪个环境中构建:
task("Build", series(CopyConfig));
function CopyConfig(cb){
if(arg.env == "dev"){
return src(['config.dev.json'])
.pipe(rename("config.json"))
.pipe(dest('./dist'));
} else if(arg.env == "prod"){
return src(['config.prod.json'])
.pipe(rename("config.json"))
.pipe(dest('./dist'));
}else if(arg.env == "local"){
return src(['config.local.json'])
.pipe(rename("config.json"))
.pipe(dest('./dist'));
}
};
如何只在开发和本地环境中导出?
尝试使用当前环境的值设置环境变量,然后将 'module.exports' 放入 if 块中。
if(process.env['ENV'] === 'dev'){
module.exports = {};
}
一种选择是使用环境变量,它可以在任何文件中访问。您可以将脚本添加到 package.json
文件:
"scripts": {
"build:dev": "NODE_ENV='development' gulp"
}
然后,在你的导出文件中,像这样:
async function AuthenticateHandler(req: Restify.Request, res: Restify.Response, next) { ... });
function shutdownServer() { ... }
module.exports.shutdownServer = shutdownServer;
// conditionally export a function
if (process.env.NODE_ENV === 'development') {
module.exports.AuthenticateHandler = AuthenticateHandler;
}