Skip to content

Instantly share code, notes, and snippets.

@AviVahl
Last active August 29, 2019 12:34
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AviVahl/40e031bd72c7264890f349020d04130a to your computer and use it in GitHub Desktop.
Save AviVahl/40e031bd72c7264890f349020d04130a to your computer and use it in GitHub Desktop.
TypeScript transformer to remove .js from import and export statements
// https://github.com/Microsoft/TypeScript/issues/16577#issuecomment-343699395
const path = require('path');
const ts = require('typescript');
const { isImportDeclaration, isExportDeclaration, isStringLiteral } = require('tsutils/typeguard/node');
function getCustomTransformers() {
return { before: [stripJsExt] }
function stripJsExt(context) {
return sourceFile => visitNode(sourceFile);
function visitNode(node) {
if ((isImportDeclaration(node) || isExportDeclaration(node)) &&
node.moduleSpecifier && isStringLiteral(node.moduleSpecifier)) {
const targetModule = node.moduleSpecifier.text;
if (targetModule.endsWith('.js')) {
const newTarget = targetModule.slice(0, targetModule.length - 3);
return isImportDeclaration(node) ?
ts.updateImportDeclaration(
node,
node.decorators,
node.modifiers,
node.importClause,
ts.createLiteral(newTarget)
) :
ts.updateExportDeclaration(
node,
node.decorators,
node.modifiers,
node.exportClause,
ts.createLiteral(newTarget)
);
}
}
return ts.visitEachChild(node, visitNode, context);
}
}
}
module.exports = {
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.bundle.js'
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json']
},
module: {
rules: [
{ test: /\.tsx?$/, loader: 'ts-loader', options: { getCustomTransformers } }
]
}
};
@lppedd
Copy link

lppedd commented Aug 29, 2019

@AviVahl understood. Thanks again for the useful advices!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment