RedDragon
RedDragon

Reputation: 2138

How to prevent module from being loaded in production in NodeJS?

As per question title, I have a module that should be used only in test, how can I prevent it from being used in production?

Upvotes: 3

Views: 1170

Answers (3)

Abhas Tandon
Abhas Tandon

Reputation: 1889

Looks like you are trying to mock some modules in NodeJS for test cases.

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. 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. 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?

Also, with require you can import modules conditionally:

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

Upvotes: 3

Sreehari
Sreehari

Reputation: 1370

Instead of adding in "dependencies", add module in "devDependencies" section of package.json

Upvotes: -1

Humble Rumble
Humble Rumble

Reputation: 1232

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:

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

Just look for the specific implementation for your specific build process.

Upvotes: 0

Related Questions