简体   繁体   English

如何防止在NodeJS中生成模块?

[英]How to prevent module from being loaded in production in NodeJS?

根据问题标题,我有一个只应该在测试中使用的模块,如何防止它在生产中使用?

Looks like you are trying to mock some modules in NodeJS for test cases. 看起来你正试图在NodeJS模拟测试用例的一些模块。

Instead of importing conditionally, a better way would be to export real or mock object conditionally. 而不是有条件地导入,更好的方法是有条件地导出真实或模拟对象。

import mockModule from './mockModule';
import realModule from './realModule';

const exported = (CONDITION) ? mockModule : realModule;
export default exported;

Also, instead of mockModule you may wish to export some empty object for your use case. 另外,您可能希望为您的用例导出一些空对象,而不是mockModule Something like: 就像是:

const exported = (CONDITION)? {} : realModule;

CONDITION to check if the test is running could be different based on some environment variable or your test suite. CONDITION检查,如果在测试运行基于一些环境变量或测试套件可能会有所不同。 Eg for mocha you can use: 例如,对于摩卡你可以使用:

var isInTest = typeof global.it === 'function';

Source: How to detect if a mocha test is running in node.js? 来源: 如何检测moc测试是否在node.js中运行?

Also, with require you can import modules conditionally: 此外,使用require您可以有条件地导入模块:

if (CONDITION) {
    const foo = require('foo');
}

It will be all down to your build process and environment variables. 这将归结为您的构建过程和环境变量。 I know for example that if you build using Wepback then in your webpack.config file you have the following code which you can add an exclusion to: 我知道例如,如果你使用Wepback构建,那么在你的webpack.config文件中你有以下代码,你可以添加一个排除:

module: {
    rules: [
        { test: /\.ts$/, loader: "ts-loader", exclude: /*myModuleToExclude*/, },
    ]
}

Just look for the specific implementation for your specific build process. 只需查看特定构建过程的具体实现。

不要添加“依赖项”,而是在package.json的“devDependencies”部分添加模块

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

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