no-duplicate-imports.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /**
  2. * @fileoverview Restrict usage of duplicate imports.
  3. * @author Simen Bekkhus
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Helpers
  8. //------------------------------------------------------------------------------
  9. const NAMED_TYPES = ["ImportSpecifier", "ExportSpecifier"];
  10. const NAMESPACE_TYPES = [
  11. "ImportNamespaceSpecifier",
  12. "ExportNamespaceSpecifier",
  13. ];
  14. //------------------------------------------------------------------------------
  15. // Rule Definition
  16. //------------------------------------------------------------------------------
  17. /**
  18. * Check if an import/export type belongs to (ImportSpecifier|ExportSpecifier) or (ImportNamespaceSpecifier|ExportNamespaceSpecifier).
  19. * @param {string} importExportType An import/export type to check.
  20. * @param {string} type Can be "named" or "namespace"
  21. * @returns {boolean} True if import/export type belongs to (ImportSpecifier|ExportSpecifier) or (ImportNamespaceSpecifier|ExportNamespaceSpecifier) and false if it doesn't.
  22. */
  23. function isImportExportSpecifier(importExportType, type) {
  24. const arrayToCheck = type === "named" ? NAMED_TYPES : NAMESPACE_TYPES;
  25. return arrayToCheck.includes(importExportType);
  26. }
  27. /**
  28. * Return the type of (import|export).
  29. * @param {ASTNode} node A node to get.
  30. * @returns {string} The type of the (import|export).
  31. */
  32. function getImportExportType(node) {
  33. if (node.specifiers && node.specifiers.length > 0) {
  34. const nodeSpecifiers = node.specifiers;
  35. const index = nodeSpecifiers.findIndex(
  36. ({ type }) =>
  37. isImportExportSpecifier(type, "named") ||
  38. isImportExportSpecifier(type, "namespace"),
  39. );
  40. const i = index > -1 ? index : 0;
  41. return nodeSpecifiers[i].type;
  42. }
  43. if (node.type === "ExportAllDeclaration") {
  44. if (node.exported) {
  45. return "ExportNamespaceSpecifier";
  46. }
  47. return "ExportAll";
  48. }
  49. return "SideEffectImport";
  50. }
  51. /**
  52. * Returns a boolean indicates if two (import|export) can be merged
  53. * @param {ASTNode} node1 A node to check.
  54. * @param {ASTNode} node2 A node to check.
  55. * @returns {boolean} True if two (import|export) can be merged, false if they can't.
  56. */
  57. function isImportExportCanBeMerged(node1, node2) {
  58. const importExportType1 = getImportExportType(node1);
  59. const importExportType2 = getImportExportType(node2);
  60. if (
  61. (node1.importKind === "type" || node1.exportKind === "type") &&
  62. (node2.importKind === "type" || node2.exportKind === "type")
  63. ) {
  64. const isDefault1 = importExportType1 === "ImportDefaultSpecifier";
  65. const isDefault2 = importExportType2 === "ImportDefaultSpecifier";
  66. const isNamed1 = isImportExportSpecifier(importExportType1, "named");
  67. const isNamed2 = isImportExportSpecifier(importExportType2, "named");
  68. if ((isDefault1 && isNamed2) || (isDefault2 && isNamed1)) {
  69. return false;
  70. }
  71. }
  72. if (
  73. (importExportType1 === "ExportAll" &&
  74. importExportType2 !== "ExportAll" &&
  75. importExportType2 !== "SideEffectImport") ||
  76. (importExportType1 !== "ExportAll" &&
  77. importExportType1 !== "SideEffectImport" &&
  78. importExportType2 === "ExportAll")
  79. ) {
  80. return false;
  81. }
  82. if (
  83. (isImportExportSpecifier(importExportType1, "namespace") &&
  84. isImportExportSpecifier(importExportType2, "named")) ||
  85. (isImportExportSpecifier(importExportType2, "namespace") &&
  86. isImportExportSpecifier(importExportType1, "named"))
  87. ) {
  88. return false;
  89. }
  90. return true;
  91. }
  92. /**
  93. * Returns a boolean if we should report (import|export).
  94. * @param {ASTNode} node A node to be reported or not.
  95. * @param {[ASTNode]} previousNodes An array contains previous nodes of the module imported or exported.
  96. * @param {boolean} allowSeparateTypeImports Whether to allow separate type and value imports.
  97. * @returns {boolean} True if the (import|export) should be reported.
  98. */
  99. function shouldReportImportExport(
  100. node,
  101. previousNodes,
  102. allowSeparateTypeImports,
  103. ) {
  104. let i = 0;
  105. while (i < previousNodes.length) {
  106. const previousNode = previousNodes[i];
  107. if (allowSeparateTypeImports) {
  108. const isTypeNode =
  109. node.importKind === "type" || node.exportKind === "type";
  110. const isTypePrevious =
  111. previousNode.importKind === "type" ||
  112. previousNode.exportKind === "type";
  113. if (isTypeNode !== isTypePrevious) {
  114. i++;
  115. continue;
  116. }
  117. }
  118. if (isImportExportCanBeMerged(node, previousNode)) {
  119. return true;
  120. }
  121. i++;
  122. }
  123. return false;
  124. }
  125. /**
  126. * Returns array contains only nodes with declarations types equal to type.
  127. * @param {[{node: ASTNode, declarationType: string}]} nodes An array contains objects, each object contains a node and a declaration type.
  128. * @param {string} type Declaration type.
  129. * @returns {[ASTNode]} An array contains only nodes with declarations types equal to type.
  130. */
  131. function getNodesByDeclarationType(nodes, type) {
  132. return nodes
  133. .filter(({ declarationType }) => declarationType === type)
  134. .map(({ node }) => node);
  135. }
  136. /**
  137. * Returns the name of the module imported or re-exported.
  138. * @param {ASTNode} node A node to get.
  139. * @returns {string} The name of the module, or empty string if no name.
  140. */
  141. function getModule(node) {
  142. if (node && node.source && node.source.value) {
  143. return node.source.value.trim();
  144. }
  145. return "";
  146. }
  147. /**
  148. * Checks if the (import|export) can be merged with at least one import or one export, and reports if so.
  149. * @param {RuleContext} context The ESLint rule context object.
  150. * @param {ASTNode} node A node to get.
  151. * @param {Map} modules A Map object contains as a key a module name and as value an array contains objects, each object contains a node and a declaration type.
  152. * @param {string} declarationType A declaration type can be an import or export.
  153. * @param {boolean} includeExports Whether or not to check for exports in addition to imports.
  154. * @param {boolean} allowSeparateTypeImports Whether to allow separate type and value imports.
  155. * @returns {void} No return value.
  156. */
  157. function checkAndReport(
  158. context,
  159. node,
  160. modules,
  161. declarationType,
  162. includeExports,
  163. allowSeparateTypeImports,
  164. ) {
  165. const module = getModule(node);
  166. if (modules.has(module)) {
  167. const previousNodes = modules.get(module);
  168. const messagesIds = [];
  169. const importNodes = getNodesByDeclarationType(previousNodes, "import");
  170. let exportNodes;
  171. if (includeExports) {
  172. exportNodes = getNodesByDeclarationType(previousNodes, "export");
  173. }
  174. if (declarationType === "import") {
  175. if (
  176. shouldReportImportExport(
  177. node,
  178. importNodes,
  179. allowSeparateTypeImports,
  180. )
  181. ) {
  182. messagesIds.push("import");
  183. }
  184. if (includeExports) {
  185. if (
  186. shouldReportImportExport(
  187. node,
  188. exportNodes,
  189. allowSeparateTypeImports,
  190. )
  191. ) {
  192. messagesIds.push("importAs");
  193. }
  194. }
  195. } else if (declarationType === "export") {
  196. if (
  197. shouldReportImportExport(
  198. node,
  199. exportNodes,
  200. allowSeparateTypeImports,
  201. )
  202. ) {
  203. messagesIds.push("export");
  204. }
  205. if (
  206. shouldReportImportExport(
  207. node,
  208. importNodes,
  209. allowSeparateTypeImports,
  210. )
  211. ) {
  212. messagesIds.push("exportAs");
  213. }
  214. }
  215. messagesIds.forEach(messageId =>
  216. context.report({
  217. node,
  218. messageId,
  219. data: {
  220. module,
  221. },
  222. }),
  223. );
  224. }
  225. }
  226. /**
  227. * @callback nodeCallback
  228. * @param {ASTNode} node A node to handle.
  229. */
  230. /**
  231. * Returns a function handling the (imports|exports) of a given file
  232. * @param {RuleContext} context The ESLint rule context object.
  233. * @param {Map} modules A Map object contains as a key a module name and as value an array contains objects, each object contains a node and a declaration type.
  234. * @param {string} declarationType A declaration type can be an import or export.
  235. * @param {boolean} includeExports Whether or not to check for exports in addition to imports.
  236. * @param {boolean} allowSeparateTypeImports Whether to allow separate type and value imports.
  237. * @returns {nodeCallback} A function passed to ESLint to handle the statement.
  238. */
  239. function handleImportsExports(
  240. context,
  241. modules,
  242. declarationType,
  243. includeExports,
  244. allowSeparateTypeImports,
  245. ) {
  246. return function (node) {
  247. const module = getModule(node);
  248. if (module) {
  249. checkAndReport(
  250. context,
  251. node,
  252. modules,
  253. declarationType,
  254. includeExports,
  255. allowSeparateTypeImports,
  256. );
  257. const currentNode = { node, declarationType };
  258. let nodes = [currentNode];
  259. if (modules.has(module)) {
  260. const previousNodes = modules.get(module);
  261. nodes = [...previousNodes, currentNode];
  262. }
  263. modules.set(module, nodes);
  264. }
  265. };
  266. }
  267. /** @type {import('../types').Rule.RuleModule} */
  268. module.exports = {
  269. meta: {
  270. dialects: ["javascript", "typescript"],
  271. language: "javascript",
  272. type: "problem",
  273. defaultOptions: [
  274. {
  275. includeExports: false,
  276. allowSeparateTypeImports: false,
  277. },
  278. ],
  279. docs: {
  280. description: "Disallow duplicate module imports",
  281. recommended: false,
  282. url: "https://eslint.org/docs/latest/rules/no-duplicate-imports",
  283. },
  284. schema: [
  285. {
  286. type: "object",
  287. properties: {
  288. includeExports: {
  289. type: "boolean",
  290. },
  291. allowSeparateTypeImports: {
  292. type: "boolean",
  293. },
  294. },
  295. additionalProperties: false,
  296. },
  297. ],
  298. messages: {
  299. import: "'{{module}}' import is duplicated.",
  300. importAs: "'{{module}}' import is duplicated as export.",
  301. export: "'{{module}}' export is duplicated.",
  302. exportAs: "'{{module}}' export is duplicated as import.",
  303. },
  304. },
  305. create(context) {
  306. const [{ includeExports, allowSeparateTypeImports }] = context.options;
  307. const modules = new Map();
  308. const handlers = {
  309. ImportDeclaration: handleImportsExports(
  310. context,
  311. modules,
  312. "import",
  313. includeExports,
  314. allowSeparateTypeImports,
  315. ),
  316. };
  317. if (includeExports) {
  318. handlers.ExportNamedDeclaration = handleImportsExports(
  319. context,
  320. modules,
  321. "export",
  322. includeExports,
  323. allowSeparateTypeImports,
  324. );
  325. handlers.ExportAllDeclaration = handleImportsExports(
  326. context,
  327. modules,
  328. "export",
  329. includeExports,
  330. allowSeparateTypeImports,
  331. );
  332. }
  333. return handlers;
  334. },
  335. };