Eslint-脚本和模块的SourceType混合体
Eslint - SourceType mixture of script and module
我们开始混合使用一些es6模块,当您在不使用sourceType:script 的情况下使用导入/导出时,esint会合理地抱怨
Parsing error: 'import' and 'export' may appear only with 'sourceType: module'at line 1 col 1
但是,如果我将sourceType更改为module,则每个具有"use strict"的文件;顶部被标记为模块中不需要严格使用。
模块是我的jsx文件,我的js文件是POJ,所以我需要这两个sourceTypes来操作。
关于如何强制esint同时使用模块和脚本,有什么想法吗?我希望避免运行两个单独的eslintrc文件和规则集,只为了一个是模块,另一个是脚本。
只要你的脚本有一个扩展,而你的模块有一个不同的扩展,那么你就可以有两个不同的配置。
// .eslintrc.json
{
// ...
// Your normal config goes here
// ...
}
使用eslint .
Lint您的普通脚本,就像您一直在做的那样。它默认为sourceType: "script"
,默认情况下拉取.eslintrc.json
,并且默认情况下仅lints *.js
文件。
// .eslintrc.modules.json
{
"extends": "./.eslintrc.json",
"parserOptions": {
"sourceType": "module"
},
// You can have additional module-specific config here if you want
}
现在,您可以使用eslint --config .eslintrc.modules.json --ext .jsx .
只对模块进行lint,这将拉取模块配置,它只是普通.eslintrc.json
的扩展,并且它只对*.jsx
文件进行lint。
我已经在根文件夹中使用选项sourceType
:script
创建了主文件。在文件夹中时/前文件.eslintrc.json
:
{
"extends": "../.eslintrc.json",
"parserOptions": {
"sourceType": "module"
}
}
现在eslint 4.1.0+中有一个更好的方法:
module.exports = {
overrides: [
{
files: [ "rollup.config.js" ],
parserOptions: { sourceType: "module" },
}
]
};
您还可以在覆盖部分中更改规则或您想要的任何内容,每个glob。
有一种既能吃蛋糕又能吃蛋糕的方法,即保留所有扩展名为.js
的文件,同时消除文件中sourceType
的歧义。
首先,就像其他答案所建议的那样,添加一个替代文件扩展名的覆盖:
{ "overrides":
[
{ "files": [ "*.js" ]
, "excludedFiles": "*unambiguous.js"
, "processor": "plugin-name/disambiguate" }
,
{ "files": [ "*.mjs" ]
, "parserOptions":
{ "sourceType": "module" } }
] }
然后是魔术:制作一个超级简单的ESLint插件,就像一样
var module_regex = /'bimport'b|'bexport'b/
module .exports =
{ processors:
{ disambiguate:
{ preprocess: (_source_string, _file_path) => {
if (module_regex .test (_source_string)) {
return [
{ text: _source_string
, filename: 'unambiguous.mjs' } ] }
else {
return [
{ text: _source_string
, filename: 'unambiguous.js' } ] } } } } }
有了这个设置,在ESLint插件消除了Javascript代码的歧义后,ESLint就可以像预期的那样理解sourceType
,而不需要更改.js
文件扩展名。
这非常适合ESLint配置/插件模型,作为一个插件,你甚至可以将"overrides"
放在插件配置中,这样你的基本配置所需要做的就是包括插件,以消除歧义。
也许可以考虑把这个放在npm上,希望这能帮助到别人。