Skip to content

Instantly share code, notes, and snippets.

@rpl
Created May 31, 2022 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpl/7b50f9d2a347c068d1b1185a0d173b09 to your computer and use it in GitHub Desktop.
Save rpl/7b50f9d2a347c068d1b1185a0d173b09 to your computer and use it in GitHub Desktop.
jscodeshift transform script used to rewrite import statements to fix incompatibility with nodejs native ES module loader

transform-add-ext-to-local-imported-modules.cjs is a small jscodeshift transformer which rewrites relative paths in the static import statements to fix an incompatibility with the nodejs native ES module loader (which requires a file extension for imports using related paths).

npx jscodeshift --parser=babylon -t transform-add-ext-to-local-imported-modules.cjs tests/functional/test.typo.run.js
/**
* This adds .js to all imports related to local modules.
*/
module.exports = function(fileInfo, api /*, options */) {
// console.log("CANARY transform called", api.jscodeshift(fileInfo.source).__paths[0].value.program.body, api.ImportDeclaration);
return api.jscodeshift(fileInfo.source)
.find("ImportDeclaration")
.filter((p) => {
return (
p.value.source.type === 'StringLiteral' &&
p.value.importKind !== 'type' &&
p.value.source.value?.startsWith('.') &&
(
!p.value.source.value?.endsWith('.js') ||
p.value.source.value?.includes('/src/')
)
);
})
.replaceWith((p) => {
if (p.value.source.value.includes('/src/')) {
p.value.source.value = p.value.source.value.replace(
'/src/',
'/lib/'
);
}
if (!p.value.source.value.endsWith('.js')) {
const {statSync} = require('fs');
const path = require('path');
let isDirectory = false;
try {
isDirectory = statSync(
path.resolve(path.dirname(fileInfo.path), p.value.source.value)
).isDirectory();
} catch (err) {
// statSync throws if the directory doesn't exist (e.g. because
// the import is actually meant to point to a file).
}
const newValue = isDirectory
? `${p.value.source.value}/index.js`
: `${p.value.source.value}.js`;
p.value.source.value = newValue;
}
console.log("Rewrote import to", p.value.source.value);
return p.value;
})
.toSource({ quote: 'single' });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment