-
-
Notifications
You must be signed in to change notification settings - Fork 104
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Resolve paths from tsconfig as webpack aliases
- Loading branch information
1 parent
016ecf0
commit 669f2d7
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
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
53 changes: 53 additions & 0 deletions
53
programs/develop/webpack/plugin-compilation/resolve-ts-path-config.ts
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import * as fs from 'fs' | ||
import * as path from 'path' | ||
import {Compiler} from 'webpack' | ||
|
||
export class ResolveTsPathsConfig { | ||
apply(compiler: Compiler) { | ||
const tsConfigPath = path.resolve(process.cwd(), 'tsconfig.json') | ||
|
||
if (fs.existsSync(tsConfigPath)) { | ||
const tsConfig = JSON.parse(fs.readFileSync(tsConfigPath, 'utf-8')) | ||
|
||
if (tsConfig.compilerOptions && tsConfig.compilerOptions.paths) { | ||
const {paths} = tsConfig.compilerOptions | ||
|
||
// Convert TS paths to Webpack alias format | ||
const alias: Record<string, string> = {} | ||
for (const key in paths) { | ||
if (paths.hasOwnProperty(key)) { | ||
const aliasKey = key.replace('/*', '') | ||
const aliasPath = path.resolve( | ||
process.cwd(), | ||
paths[key][0].replace('/*', '') | ||
) | ||
alias[aliasKey] = aliasPath | ||
} | ||
} | ||
|
||
// Append to Webpack resolve.alias | ||
if (!compiler.options.resolve) { | ||
compiler.options.resolve = {} | ||
} | ||
if (!compiler.options.resolve.alias) { | ||
compiler.options.resolve.alias = {} | ||
} | ||
compiler.options.resolve.alias = { | ||
...compiler.options.resolve.alias, | ||
...alias | ||
} | ||
|
||
if (process.env.EXTENSION_ENV === 'development') { | ||
console.log( | ||
'Successfully appended TypeScript paths to Webpack alias:', | ||
alias | ||
) | ||
} | ||
} else { | ||
// No paths found in tsconfig.json. Continue silently... | ||
} | ||
} else { | ||
// tsconfig.json not found. Continue silently... | ||
} | ||
} | ||
} |