非常教程

Webpack参考手册

装载 | Loaders

jshint-loader

对所需的 JavaScript 文件运行 JSHint。

安装

npm i jshint-loader --save

用法

在 webpack 配置中启用 jshint loader:

module.exports = {
    module: {
        rules: [
            {
                test: /\.js$/, // include .js files
                enforce: "pre", // preload the jshint loader
                exclude: /node_modules/, // exclude any and all files in the node_modules folder
                use: [
                    {
                        loader: "jshint-loader"
                    }
                ]
            }
        ]
    },

    // more options in the optional jshint object
    jshint: {
        // any jshint option http://www.jshint.com/docs/options/
        // i. e.
        camelcase: true,

        // jshint errors are displayed by default as warnings
        // set emitErrors to true to display them as errors
        emitErrors: false,

        // jshint to not interrupt the compilation
        // if you want any file with jshint errors to fail
        // set failOnHint to true
        failOnHint: false,

        // custom reporter function
        reporter: function(errors) { }
    }
}

自定义 reporter

在默认情况下,jshint-loader 会提供一个默认的报告方法。

然而,如果你想自定义报告函数,你可以在 jshint 配置下 key 为 report 下的配置项里传入自定义的函数。(参考上文的用法

然后,jshint 将会生成与以下示例结构一致的 错误/警告信息(数组)给报告函数。

[
{
    id:        [string, usually '(error)'],
    code:      [string, error/warning code],
    reason:    [string, error/warning message],
    evidence:  [string, a piece of code that generated this error]
    line:      [number]
    character: [number]
    scope:     [string, message scope;
                usually '(main)' unless the code was eval'ed]

    [+ a few other legacy fields that you don't need to worry about.]
},
// ...
// more errors/warnings
]

报告函数会将 loader 的上下文信息保存在 this 后执行。你可以使用 this.emitWarning(...) 或者 this.emitError(...) 方法,手动触发信息的报告。请参考关于 loader 上下文的 webpack 文档.

注意:jshint reporters 是与 jshint-loader 不兼容的! 这是因为 reporter 的输入来源,只能从一个文件,而不能同时从多个文件读取。在这种方式下的错误报告,是与 jshint 的传统 reporters 不一样的, 因为 loader 插件(例如 jshint-loader)是会在每一个源文件上执行的,因此它们的报告函数也会分别对应每一个源文件上执行。

webpack CLI 中的输出通常是:

...

WARNING in ./path/to/file.js
<reporter output>

...