Last active
August 29, 2019 12:34
-
-
Save AviVahl/40e031bd72c7264890f349020d04130a to your computer and use it in GitHub Desktop.
TypeScript transformer to remove .js from import and export statements
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
// 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 } } | |
] | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@AviVahl understood. Thanks again for the useful advices!