Skip to content

Commit

Permalink
Resolve paths from tsconfig as webpack aliases
Browse files Browse the repository at this point in the history
  • Loading branch information
cezaraugusto committed Sep 30, 2024
1 parent 016ecf0 commit 669f2d7
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
3 changes: 3 additions & 0 deletions programs/develop/webpack/plugin-compilation/index.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand All @@ -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) => {
Expand Down
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...
}
}
}

0 comments on commit 669f2d7

Please sign in to comment.