Skip to content

Commit

Permalink
build: mjs files import other files using full paths with exten… (#2379)
Browse files Browse the repository at this point in the history
Motivation #2277
  • Loading branch information
IvanGoncharov authored Jan 21, 2020
1 parent 20b0d41 commit 4980779
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .babelrc
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
"presets": [["@babel/preset-env", { "modules": "commonjs" }]]
},
"mjs": {
"presets": [["@babel/preset-env", { "modules": false }]]
"presets": [["@babel/preset-env", { "modules": false }]],
"plugins": ['./resources/add-extension-to-import-paths']
}
}
},
Expand Down
43 changes: 43 additions & 0 deletions resources/add-extension-to-import-paths.js
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);
}
}
}
};

0 comments on commit 4980779

Please sign in to comment.