UNPKG

2.1 kBJavaScriptView Raw
1const fs = require('fs-extra');
2const path = require('path');
3
4const resolveImportPathExtensions = (filePath) => {
5 return {
6 visitor: {
7 'ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration': (path) => {
8 if (path.node.source) {
9 path.node.source.value =
10 checkForExtension(filePath, path.node.source.value, '.mjs') ||
11 checkForExtension(filePath, path.node.source.value, '.js') ||
12 checkForExtension(filePath, path.node.source.value, '.ts') ||
13 checkForExtension(filePath, path.node.source.value, '.jsx') ||
14 checkForExtension(filePath, path.node.source.value, '.tsx');
15 }
16 }
17 }
18 };
19};
20
21module.exports = resolveImportPathExtensions;
22
23function checkForExtension(filePath, importPath, extension) {
24 const filePathDirectory = filePath.slice(0, filePath.lastIndexOf('/') + 1);
25 const absolutePath = path.resolve(path.join(filePathDirectory, importPath));
26
27 if (hasExtension(importPath, extension)) {
28 return importPath;
29 }
30 else if (fs.existsSync(`${absolutePath}${extension}`)) {
31 return `${importPath}${extension}`;
32 }
33 else if (fs.existsSync(`${absolutePath}/index.mjs`)) {
34 return `${importPath}/index.mjs`;
35 }
36 else if ((fs.existsSync(`${absolutePath}/index.js`))) {
37 return `${importPath}/index.js`;
38 }
39 else if ((fs.existsSync(`${absolutePath}/index.ts`))) {
40 return `${importPath}/index.ts`;
41 }
42 else if ((fs.existsSync(`${absolutePath}/index.jsx`))) {
43 return `${importPath}/index.jsx`;
44 }
45 else if ((fs.existsSync(`${absolutePath}/index.tsx`))) {
46 return `${importPath}/index.tsx`;
47 }
48
49 return null;
50}
51
52function hasExtension(path, extension) {
53 const pathBackward = backwardsify(path);
54 const extensionBackward = backwardsify(extension);
55
56 return pathBackward.indexOf(extensionBackward) === 0;
57}
58
59function backwardsify(theString) {
60 return theString.split('').reverse().join('');
61}