no-duplicate-imports.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. (importExportType1 === "ExportAll" &&
  62. importExportType2 !== "ExportAll" &&
  63. importExportType2 !== "SideEffectImport") ||
  64. (importExportType1 !== "ExportAll" &&
  65. importExportType1 !== "SideEffectImport" &&
  66. importExportType2 === "ExportAll")
  67. ) {
  68. return false;
  69. }
  70. if (
  71. (isImportExportSpecifier(importExportType1, "namespace") &&
  72. isImportExportSpecifier(importExportType2, "named")) ||
  73. (isImportExportSpecifier(importExportType2, "namespace") &&
  74. isImportExportSpecifier(importExportType1, "named"))
  75. ) {
  76. return false;
  77. }
  78. return true;
  79. }
  80. /**
  81. * Returns a boolean if we should report (import|export).
  82. * @param {ASTNode} node A node to be reported or not.
  83. * @param {[ASTNode]} previousNodes An array contains previous nodes of the module imported or exported.
  84. * @returns {boolean} True if the (import|export) should be reported.
  85. */
  86. function shouldReportImportExport(node, previousNodes) {
  87. let i = 0;
  88. while (i < previousNodes.length) {
  89. if (isImportExportCanBeMerged(node, previousNodes[i])) {
  90. return true;
  91. }
  92. i++;
  93. }
  94. return false;
  95. }
  96. /**
  97. * Returns array contains only nodes with declarations types equal to type.
  98. * @param {[{node: ASTNode, declarationType: string}]} nodes An array contains objects, each object contains a node and a declaration type.
  99. * @param {string} type Declaration type.
  100. * @returns {[ASTNode]} An array contains only nodes with declarations types equal to type.
  101. */
  102. function getNodesByDeclarationType(nodes, type) {
  103. return nodes
  104. .filter(({ declarationType }) => declarationType === type)
  105. .map(({ node }) => node);
  106. }
  107. /**
  108. * Returns the name of the module imported or re-exported.
  109. * @param {ASTNode} node A node to get.
  110. * @returns {string} The name of the module, or empty string if no name.
  111. */
  112. function getModule(node) {
  113. if (node && node.source && node.source.value) {
  114. return node.source.value.trim();
  115. }
  116. return "";
  117. }
  118. /**
  119. * Checks if the (import|export) can be merged with at least one import or one export, and reports if so.
  120. * @param {RuleContext} context The ESLint rule context object.
  121. * @param {ASTNode} node A node to get.
  122. * @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.
  123. * @param {string} declarationType A declaration type can be an import or export.
  124. * @param {boolean} includeExports Whether or not to check for exports in addition to imports.
  125. * @returns {void} No return value.
  126. */
  127. function checkAndReport(
  128. context,
  129. node,
  130. modules,
  131. declarationType,
  132. includeExports
  133. ) {
  134. const module = getModule(node);
  135. if (modules.has(module)) {
  136. const previousNodes = modules.get(module);
  137. const messagesIds = [];
  138. const importNodes = getNodesByDeclarationType(previousNodes, "import");
  139. let exportNodes;
  140. if (includeExports) {
  141. exportNodes = getNodesByDeclarationType(previousNodes, "export");
  142. }
  143. if (declarationType === "import") {
  144. if (shouldReportImportExport(node, importNodes)) {
  145. messagesIds.push("import");
  146. }
  147. if (includeExports) {
  148. if (shouldReportImportExport(node, exportNodes)) {
  149. messagesIds.push("importAs");
  150. }
  151. }
  152. } else if (declarationType === "export") {
  153. if (shouldReportImportExport(node, exportNodes)) {
  154. messagesIds.push("export");
  155. }
  156. if (shouldReportImportExport(node, importNodes)) {
  157. messagesIds.push("exportAs");
  158. }
  159. }
  160. messagesIds.forEach(messageId =>
  161. context.report({
  162. node,
  163. messageId,
  164. data: {
  165. module
  166. }
  167. }));
  168. }
  169. }
  170. /**
  171. * @callback nodeCallback
  172. * @param {ASTNode} node A node to handle.
  173. */
  174. /**
  175. * Returns a function handling the (imports|exports) of a given file
  176. * @param {RuleContext} context The ESLint rule context object.
  177. * @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.
  178. * @param {string} declarationType A declaration type can be an import or export.
  179. * @param {boolean} includeExports Whether or not to check for exports in addition to imports.
  180. * @returns {nodeCallback} A function passed to ESLint to handle the statement.
  181. */
  182. function handleImportsExports(
  183. context,
  184. modules,
  185. declarationType,
  186. includeExports
  187. ) {
  188. return function(node) {
  189. const module = getModule(node);
  190. if (module) {
  191. checkAndReport(
  192. context,
  193. node,
  194. modules,
  195. declarationType,
  196. includeExports
  197. );
  198. const currentNode = { node, declarationType };
  199. let nodes = [currentNode];
  200. if (modules.has(module)) {
  201. const previousNodes = modules.get(module);
  202. nodes = [...previousNodes, currentNode];
  203. }
  204. modules.set(module, nodes);
  205. }
  206. };
  207. }
  208. /** @type {import('../shared/types').Rule} */
  209. module.exports = {
  210. meta: {
  211. type: "problem",
  212. docs: {
  213. description: "Disallow duplicate module imports",
  214. recommended: false,
  215. url: "https://eslint.org/docs/rules/no-duplicate-imports"
  216. },
  217. schema: [
  218. {
  219. type: "object",
  220. properties: {
  221. includeExports: {
  222. type: "boolean",
  223. default: false
  224. }
  225. },
  226. additionalProperties: false
  227. }
  228. ],
  229. messages: {
  230. import: "'{{module}}' import is duplicated.",
  231. importAs: "'{{module}}' import is duplicated as export.",
  232. export: "'{{module}}' export is duplicated.",
  233. exportAs: "'{{module}}' export is duplicated as import."
  234. }
  235. },
  236. create(context) {
  237. const includeExports = (context.options[0] || {}).includeExports,
  238. modules = new Map();
  239. const handlers = {
  240. ImportDeclaration: handleImportsExports(
  241. context,
  242. modules,
  243. "import",
  244. includeExports
  245. )
  246. };
  247. if (includeExports) {
  248. handlers.ExportNamedDeclaration = handleImportsExports(
  249. context,
  250. modules,
  251. "export",
  252. includeExports
  253. );
  254. handlers.ExportAllDeclaration = handleImportsExports(
  255. context,
  256. modules,
  257. "export",
  258. includeExports
  259. );
  260. }
  261. return handlers;
  262. }
  263. };