eslint-plugin-vue
Version:
Official ESLint plugin for Vue.js
75 lines (74 loc) • 2.61 kB
JavaScript
const require_vue3_export_names = require("../utils/vue3-export-names.json.js");
// lib/rules/prefer-import-from-vue.ts
/**
* @author Yosuke Ota
* See LICENSE file in root directory for full license.
*/
const vue3ExportNames = new Set(require_vue3_export_names.default);
const TARGET_AT_VUE_MODULES = /* @__PURE__ */ new Set([
"@vue/runtime-dom",
"@vue/runtime-core",
"@vue/reactivity",
"@vue/shared"
]);
function* extractSpecifierNames(specifier) {
switch (specifier.type) {
case "ImportDefaultSpecifier":
yield "default";
break;
case "ImportNamespaceSpecifier":
yield null;
break;
case "ImportSpecifier": yield specifier.imported.name;
}
}
function* extractImportNames(node) {
for (const specifier of node.specifiers) yield* extractSpecifierNames(specifier);
}
var prefer_import_from_vue_default = {
meta: {
type: "suggestion",
docs: {
description: "enforce import from 'vue' instead of import from '@vue/*'",
categories: ["vue3-essential"],
url: "https://eslint.vuejs.org/rules/prefer-import-from-vue.html"
},
fixable: "code",
schema: [],
messages: { importedAtVue: "Import from 'vue' instead of '{{source}}'." }
},
create(context) {
/**
* `names` are the named bindings imported or exported from the source.
*/
function verifySource(source, isFixable, names) {
if (!TARGET_AT_VUE_MODULES.has(source.value) || names.length > 0 && names.every((name) => !vue3ExportNames.has(name))) return;
context.report({
node: source,
messageId: "importedAtVue",
data: { source: source.value },
fix: isFixable() ? (fixer) => fixer.replaceTextRange([source.range[0] + 1, source.range[1] - 1], "vue") : null
});
}
return {
ImportDeclaration(node) {
if (node.specifiers.length === 0 && context.filename.endsWith(".d.ts")) return;
const importedNames = node.specifiers.every((specifier) => specifier.type === "ImportSpecifier") ? node.specifiers.map((specifier) => specifier.imported.name) : [];
verifySource(node.source, () => {
for (const name of extractImportNames(node)) if (name == null || !vue3ExportNames.has(name)) return false;
return true;
}, importedNames);
},
ExportNamedDeclaration(node) {
if (node.source) verifySource(node.source, () => {
for (const specifier of node.specifiers) if (!vue3ExportNames.has(specifier.local.name)) return false;
return true;
}, node.specifiers.map((specifier) => specifier.local.name));
},
ExportAllDeclaration(node) {
verifySource(node.source, () => false, []);
}
};
}
};
exports.default = prefer_import_from_vue_default;