Skip to content

Commit 4980779

Browse files
build: mjs files import other files using full paths with exten… (#2379)
Motivation #2277
1 parent 20b0d41 commit 4980779

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

.babelrc

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@
1919
"presets": [["@babel/preset-env", { "modules": "commonjs" }]]
2020
},
2121
"mjs": {
22-
"presets": [["@babel/preset-env", { "modules": false }]]
22+
"presets": [["@babel/preset-env", { "modules": false }]],
23+
"plugins": ['./resources/add-extension-to-import-paths']
2324
}
2425
}
2526
},
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// @noflow
2+
3+
'use strict';
4+
5+
/**
6+
* Adds extension to all paths imported inside MJS files
7+
*
8+
* Transforms:
9+
*
10+
* import { foo } from './bar';
11+
* export { foo } from './bar';
12+
*
13+
* to:
14+
*
15+
* import { foo } from './bar.mjs';
16+
* export { foo } from './bar.mjs';
17+
*
18+
*/
19+
module.exports = function addExtensionToImportPaths(context) {
20+
const { types } = context;
21+
22+
return {
23+
visitor: {
24+
ImportDeclaration: replaceImportPath,
25+
ExportNamedDeclaration: replaceImportPath,
26+
},
27+
};
28+
29+
function replaceImportPath(path) {
30+
// bail if the declaration doesn't have a source, e.g. "export { foo };"
31+
if (!path.node.source) {
32+
return;
33+
}
34+
35+
const source = path.node.source.value;
36+
if (source.startsWith('./') || source.startsWith('../')) {
37+
if (!source.endsWith('.mjs')) {
38+
const newSourceNode = types.stringLiteral(source + '.mjs');
39+
path.get('source').replaceWith(newSourceNode);
40+
}
41+
}
42+
}
43+
};

0 commit comments

Comments
 (0)