有没有办法让webpack知道是否未声明全局?

时间:2016-07-25 08:17:46

标签: javascript ecmascript-6 webpack babeljs

我使用了一些外部设备(谷歌的js是一个),我在文件的顶部有'use strict'个声明。我知道我可以使用webpack解析配置参数伪造导入,但这只允许我导入不属于源的模块。

我喜欢一个没有进口的全球化的"或者说,在webpack处理时会抛出错误。

举个例子:

var foo = bar

我希望bar(未声明或导入)与'use strict'一起出错。

我正在使用webpack 1.13.1

1 个答案:

答案 0 :(得分:1)

您可以借助ESLintno-undef rule来阻止使用未定义变量构建包。

准备此解决方案的包

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

您应该配置.eslintrc

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

webpack.config.js中,您必须添加此行以支持使用ESLint进行linting

 
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
    },
    // ...
};

此配置会给您带来这种错误

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)
相关问题