-
Notifications
You must be signed in to change notification settings - Fork 2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
build: mjs files import other files using full paths with exten… (#2379)
Motivation #2277
- Loading branch information
1 parent
20b0d41
commit 4980779
Showing
2 changed files
with
45 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
// @noflow | ||
|
||
'use strict'; | ||
|
||
/** | ||
* Adds extension to all paths imported inside MJS files | ||
* | ||
* Transforms: | ||
* | ||
* import { foo } from './bar'; | ||
* export { foo } from './bar'; | ||
* | ||
* to: | ||
* | ||
* import { foo } from './bar.mjs'; | ||
* export { foo } from './bar.mjs'; | ||
* | ||
*/ | ||
module.exports = function addExtensionToImportPaths(context) { | ||
const { types } = context; | ||
|
||
return { | ||
visitor: { | ||
ImportDeclaration: replaceImportPath, | ||
ExportNamedDeclaration: replaceImportPath, | ||
}, | ||
}; | ||
|
||
function replaceImportPath(path) { | ||
// bail if the declaration doesn't have a source, e.g. "export { foo };" | ||
if (!path.node.source) { | ||
return; | ||
} | ||
|
||
const source = path.node.source.value; | ||
if (source.startsWith('./') || source.startsWith('../')) { | ||
if (!source.endsWith('.mjs')) { | ||
const newSourceNode = types.stringLiteral(source + '.mjs'); | ||
path.get('source').replaceWith(newSourceNode); | ||
} | ||
} | ||
} | ||
}; |