Skip to content

Instantly share code, notes, and snippets.

@iahu
Last active April 29, 2021 08:52
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 iahu/8e63495ccdd79e3db63054522a8f30f7 to your computer and use it in GitHub Desktop.
Save iahu/8e63495ccdd79e3db63054522a8f30f7 to your computer and use it in GitHub Desktop.
importjs use tsconfig paths
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