UNPKG

2.99 kBJavaScriptView Raw
1const path = require('path')
2
3module.exports = (api, options) => {
4 if (options.lintOnSave) {
5 const extensions = require('./eslintOptions').extensions(api)
6 // 优先使用用户自己安装的 eslint 版本
7 const { resolveModule, loadModule } = require('@megalo/cli-share-utils')
8 const cwd = api.getCwd()
9 const eslintPkg =
10 loadModule('eslint/package.json', cwd, true) ||
11 require('eslint/package.json')
12
13 // 当 eslint 配置文件修改时,eslint-loader 处理的其实还是缓存的代码(若开启了缓存的话)
14 // 所以必须手动生成一个缓存标志符来规避这个问题,这里使用包和用户对包的配置内容作为变量来生成标志符
15 const { cacheIdentifier } = api.genCacheConfig(
16 'eslint-loader',
17 {
18 'eslint-loader': require('eslint-loader/package.json').version,
19 eslint: eslintPkg.version
20 },
21 [
22 '.eslintrc.js',
23 '.eslintrc.yaml',
24 '.eslintrc.yml',
25 '.eslintrc.json',
26 '.eslintrc',
27 'package.json'
28 ]
29 )
30
31 api.chainWebpack(webpackConfig => {
32 webpackConfig.resolveLoader.modules.prepend(
33 path.join(__dirname, 'node_modules')
34 )
35
36 const { lintOnSave } = options
37 const allWarnings = lintOnSave === true || lintOnSave === 'warning'
38 const allErrors = lintOnSave === 'error'
39
40 webpackConfig.module
41 .rule('eslint')
42 .pre()
43 .exclude
44 .add(/node_modules/)
45 .add(require('path').dirname(require.resolve('@testxcx/cli-service')))
46 .end()
47 .test(/\.(vue|(j|t)sx?)$/)
48 .use('eslint-loader')
49 .loader('eslint-loader')
50 .options({
51 extensions,
52 cache: true,
53 cacheIdentifier,
54 emitWarning: allWarnings,
55 // only emit errors in production mode.
56 emitError: allErrors,
57 eslintPath: resolveModule('eslint', cwd) || require.resolve('eslint'),
58 formatter:
59 loadModule('eslint/lib/formatters/codeframe', cwd, true) ||
60 require('eslint/lib/formatters/codeframe')
61 })
62 })
63 }
64
65 api.registerCommand(
66 'lint',
67 {
68 description: 'lint and fix source files',
69 usage: 'megalo-cli-service lint [options] [...files]',
70 options: {
71 '--format [formatter]': 'specify formatter (default: codeframe)',
72 '--no-fix': 'do not fix errors or warnings',
73 '--no-fix-warnings': 'fix errors, but do not fix warnings',
74 '--max-errors [limit]':
75 'specify number of errors to make build failed (default: 0)',
76 '--max-warnings [limit]':
77 'specify number of warnings to make build failed (default: Infinity)'
78 },
79 details:
80 'For more options, see https://eslint.org/docs/user-guide/command-line-interface#options'
81 },
82 args => {
83 require('./lint')(args, api)
84 }
85 )
86}