Last active
April 29, 2021 08:52
-
-
Save iahu/8e63495ccdd79e3db63054522a8f30f7 to your computer and use it in GitHub Desktop.
importjs use tsconfig paths
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
const Path = require('path'); | |
const tsconfig = require('./tsconfig.json'); | |
const baseUrl = tsconfig.compilerOptions.baseUrl; | |
const paths = tsconfig.compilerOptions.paths; | |
// 优先使用短的 key | |
const pathKeys = Object.keys(paths).sort((a, b) => b.length - a.length); | |
const removeWired = (str) => str.replace(/\*$/, ''); | |
const rewriteLodash = ({ moduleName, importStatement }) => { | |
if (moduleName === 'lodash') { | |
// import module from "lodash" | |
const match = importStatement.match(/\{\s?(\S+)\s?\}/); | |
const name = match[1]; | |
return `import ${name} from "lodash/${name}"`; | |
} | |
}; | |
module.exports = { | |
maxLineLength: 120, | |
useUnsafeRequireParsing: true, | |
moduleNameFormatter({ moduleName, pathToCurrentFile }) { | |
const pathToCurrentDir = Path.dirname(pathToCurrentFile); | |
const aModuleName = Path.resolve(pathToCurrentDir, moduleName); | |
let moduleAlias = moduleName; | |
pathKeys.some((key) => { | |
const aliasKey = removeWired(key); | |
return paths[key].some((path) => { | |
const resolvedPath = Path.resolve(baseUrl, removeWired(path)); | |
const aliasPath = Path.relative(resolvedPath, aModuleName); | |
if (moduleName.startsWith('../../')) { | |
moduleAlias = aliasKey + aliasPath; | |
} | |
}); | |
}); | |
return moduleAlias; | |
}, | |
importStatementFormatter(props) { | |
return rewriteLodash(props) || props.importStatement; | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment