From 669f2d7dfd62907b0979335f7fc69544961944fc Mon Sep 17 00:00:00 2001 From: Cezar Augusto Date: Mon, 30 Sep 2024 19:48:09 -0300 Subject: [PATCH] Resolve paths from tsconfig as webpack aliases --- .../webpack/plugin-compilation/index.ts | 3 ++ .../resolve-ts-path-config.ts | 53 +++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 programs/develop/webpack/plugin-compilation/resolve-ts-path-config.ts diff --git a/programs/develop/webpack/plugin-compilation/index.ts b/programs/develop/webpack/plugin-compilation/index.ts index dbfac355..9dc17a67 100644 --- a/programs/develop/webpack/plugin-compilation/index.ts +++ b/programs/develop/webpack/plugin-compilation/index.ts @@ -1,6 +1,7 @@ import {Compiler} from 'webpack' import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin' import {EnvPlugin} from './env' +import {ResolveTsPathsConfig} from './resolve-ts-path-config' import {CleanDistFolderPlugin} from './clean-dist' import * as messages from '../lib/messages' @@ -26,6 +27,8 @@ export class CompilationPlugin { browser: this.browser }).apply(compiler) + new ResolveTsPathsConfig().apply(compiler) + new CleanDistFolderPlugin().apply(compiler) compiler.hooks.done.tap('develop:brand', (stats) => { diff --git a/programs/develop/webpack/plugin-compilation/resolve-ts-path-config.ts b/programs/develop/webpack/plugin-compilation/resolve-ts-path-config.ts new file mode 100644 index 00000000..f0b943d2 --- /dev/null +++ b/programs/develop/webpack/plugin-compilation/resolve-ts-path-config.ts @@ -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 = {} + 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... + } + } +}