Inspired by marzelin/convert-tsconfig-paths-to-webpack-aliases.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const fs = require('fs');
const path = require('path');
const get = require('lodash/get');
const JSON5 = require('json5');

/**
* convert tsconfig.json paths to webpack alias
*/
const convertTSConfigPaths2Aliases = () => {
const tsConfigPath = path.resolve(process.cwd(), './tsconfig.json');

try {
if (fs.existsSync(tsConfigPath)) {
// dealing with json file with comments, we use json5 to parse tsconfig.json instead of requiring directly
const tsConfig = JSON5.parse(fs.readFileSync(tsConfigPath));
let { baseUrl, paths } = get(tsConfig, 'compilerOptions', {});

if (paths) {
baseUrl = baseUrl ? path.resolve(process.cwd(), baseUrl) : process.cwd();

const replaceGlobs = (path) => path.replace(/(\/\*\*)*\/\*$/, '');

return Object.keys(paths).reduce((aliases, pathName) => {
const alias = replaceGlobs(pathName);
const aliasPath = replaceGlobs(paths[pathName][0]);
aliases[alias] = path.resolve(baseUrl, aliasPath);
return aliases;
}, {});
}
}
} catch (err) {
console.error(err);
return {};
}

return {};
};

Usage

1
2
3
4
5
6
7
8
9
// webpack.js

module.exports = {
resolve: {
alias: {
...convertTSConfigPaths2Aliases(),
}
}
};