chrisp
chrisp

Reputation: 2249

Is there a way for webpack to know if a global is not declared?

I'm using some externals (google's js being one), and I have 'use strict' statement at the top of the file. I know I can fake imports with webpack's resolve config parameter, but that only allows me to import modules that aren't a part of the source.

I'd like a global that wasn't "imported" or like, would throw an error when webpack processes.

As an example:

var foo = bar

I'd expect bar (not declared or imported) would be an error with 'use strict'.

I'm using webpack 1.13.1

Upvotes: 1

Views: 92

Answers (1)

Everettss
Everettss

Reputation: 16049

You can prevent building packages with undefined variables with help of ESLint and no-undef rule.

Prepare packages for this solution

npm install eslint eslint-loader eslint-friendly-formatter --save-dev

You should configure .eslintrc

{
    "env": {
        "browser": true,
        "node": true,
        "es6": true
    },
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module"
    },
    "rules": {
        "no-undef": 2 // <-- ERROR on not defined variables
    }
}

In your webpack.config.js you must add this lines to support linting with ESLint

module.exports = {
    loaders: [
        {
            test: /\.js$/,
            loader: 'eslint-loader',
            exclude: /(node_modules|bower_components)/
        },
        // ...
    ],
    eslint: {
        failOnError: true, // block build on non passed linting
        configFile: '.eslintrc', // path to your .eslintrc
        formatter: require('eslint-friendly-formatter') // better error report
    },
    // ...
};

This configs gives you this kind of error

ERROR in ./src/example.js
Module build failed: Error: Module failed because of a eslint error.

  ✘  http://eslint.org/docs/rules/no-undef  'bar' is not defined
  /yourpath/src/example.js:2:11
  var foo = bar;
             ^


✘ 1 problem (1 error, 0 warnings)

Upvotes: 1

Related Questions