0

I'm using TypeScript, Mocha (with mocha-typescript plugin) for testing and WebPack for build in my application.

Recently I decided to add DefinePlugin for WebPack to separate configs for prod and dev environments:

import { AppSettings as DevSettings } from './appSettings.dev'
import { AppSettings as ProdSettings } from './appSettings.prod'

declare var __ENVIRONMENT__: string;

let settings = __ENVIRONMENT__ === 'prod' ? ProdSettings : DevSettings

export let AppSettings = settings;

In snippet above there is a global variable __ENVIRONMENT__ , which helps to choose settings I want to use. This variable is defined in webpack.config.js as follows:

module.exports = function(env) {
    var config = {
        // ...
        plugins: [
            new ExtendedDefinePlugin({
                __ENVIRONMENT__: env === 'prod' ? 'prod' : 'dev',
            })
        ]
        // ...
    }

    return config;
}

So I change tests execution in package.json to

"test": "webpack --env=dev && mocha --recursive"

If I call "test", mocha throw error (webpack builds files correctly):

ReferenceError: __ENVIRONMENT__ is not defined

Testing watcher also won't work:

"test-watch": "mocha-typescript-watch"

throwing error "Exited with 1".

Is it possible to bring them work together? Or shall I use another way for testing?

2
  • DefinePlugin should literally substitute __ENVIRONMENT__ with 'prod' or 'dev' in the build output - are you sure that substitution is working for the browser? Commented Jun 17, 2017 at 18:58
  • 1
    @Catalyst, yes it is. But it's not a root cause of this circumstance - I just didn't understand fully concepts of mocha and webpack. Commented Jun 20, 2017 at 11:15

1 Answer 1

1

Ok, as I eventually got I was using it in wrong manner.

It's more correctly to set up variable related to Node in webpack.config.js:

module.exports = function(env) {
    var config = {
        // ...
        plugins: [
            new ExtendedDefinePlugin({
                'process.env': {
                    'NODE_ENV': env === 'prod' ? 'prod' : 'dev',
                }
            })
        ]
        // ...
    }

    return config;
}

And use it whenever necessary like:

declare var process: any;

export let AppSettings = process.env.NODE_ENV === 'prod' ? ProdSettings : DevSettings;

Therefore my Mocha tests run well (because they are being executed in Node, not in browser).

Sign up to request clarification or add additional context in comments.

1 Comment

I don't get it what makes your code work. NODE_ENV? as a string? is "process.env" something that node can identify?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.