有没有一种方法可以让webpack知道是否没有声明全局

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

本文关键字:webpack 是否 全局 声明 一种 方法 有没有      更新时间:2023-09-26

我正在使用一些外部语言(谷歌的js就是其中之一),并且我在文件的顶部有'use strict'语句。我知道我可以用webpack的resolf-config参数伪造导入,但这只允许我导入不属于源代码的模块。

我想要一个不是"导入"的全局,或者类似的,在webpack处理时会抛出错误。

例如:

var foo = bar

我认为bar(未声明或导入)将是'use strict'的错误。

我使用的是webpack 1.13.1

您可以在ESLint和no-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)