[英]How to setup eslint to detect lodash as global only in single file vue components?
#我的用例
我有一個 utils mixin 模塊,它將 lodash 作為一種方法注入到所有.vue
(單文件組件)組件中:
// utilsMixin.js
import _ from 'lodash';
import moment from 'moment';
export default {
computed: {
_: () => _,
moment: () => moment,
},
};
// main.js
// ...
import utilsMixin from './utilsMixin';
Vue.mixin(utilsMixin);
因此,我所有的項目都可以使用_
和moment
作為方法。
#問題如果我在<template>
部分使用_
,則不會出現 linter 問題,因為_
在 vue 中隱藏在this
變量中:
// MyFancyComponent.vue
<template>
<myComponent
v-for="item in _.get(this, 'myObject.collection', [])"
>
<div> {{ item }} </div>
</myComponent>
但是當我在<script>
部分使用它時:
// MyFancyComponent.vue
// ...
<script>
export default {
name: 'MyFancyComponent',
methods: {
find: ()=> _.find // [eslint] '_' is not defined. [no-undef]
};
</script>
來自[eslint] '_' is not defined. [no-undef]
[eslint] '_' is not defined. [no-undef]
問題,但我仍然可以在不導入_
的情況下使用它,並且我可以通過聲明全局 lodash 來阻止 linter 抱怨:
/* global _ */
請注意,我還有其他.js
文件沒有 lodash 作為全局文件,如果我在那里使用 lodash,我需要 linter 來抱怨:
#Expected behavior 我希望 '_' 僅在我的 vue 單文件組件中被檢測為全局變量,但在我的 JavaScript 文件中未定義(因此我需要在.js
文件中導入 lodash)。
#Intuitive 解決方案我希望能夠在.eslintrc.js
中配置只能在單個文件組件中工作的全局變量。 作為一種方法,它可能看起來像:
// .eslintrc.js
// ...
globals: {
vue: {
'_': false,
moment: false
},
js: {
process: false,
isFinite: true
}
},
// ...
你的問題是你錯過了 Vue.js 如何將它注入到你的組件中。 如果您在 Vue.js 中(在腳本中)正確使用 Mixin,如下所示:
// MyFancyComponent.vue // ... <script> export default { name: 'MyFancyComponent', methods: { find(...args) { return this._.find.bind(this._, args); }// [eslint] '_' is not defined. [no-undef] }; </script>
你使用this._
來引用 Lodash 是因為你已經將它綁定到組件的實例上,而不是讓它成為一個全局引用的對象。 它工作的原因,但是 ESLint 抱怨是因為你已經將庫作為全局對象導入到你的 mixin 中,但是你沒有在這個特定的文件中導入它,所以 ESLint 抱怨是因為它不知道你做了在另一個文件中進行全局導入,並將其綁定到每個單獨的組件,以使其可用於這些單獨的組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.