Skip to content

Commit

Permalink
fix: path remapping in types build output
Browse files Browse the repository at this point in the history
- fixes "node_modules/@flex-development/tutils/types/guards/is-node-env.guard.d.ts(1,21): error TS2307: Cannot find module @tutils/enums/node-env.enum or its corresponding type declarations"
  • Loading branch information
unicornware committed Oct 16, 2021
1 parent 6fd8837 commit 78d512a
Show file tree
Hide file tree
Showing 4 changed files with 218 additions and 282 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,11 @@
"prettier-plugin-sh": "0.7.1",
"read-pkg": "7.0.0",
"replace-in-file": "6.2.0",
"resolve-tspaths": "0.1.1",
"rimraf": "3.0.2",
"shelljs": "0.8.4",
"ts-jest": "27.0.6",
"ts-node": "10.3.0",
"tsc-alias": "1.3.10",
"tsc-prog": "2.2.1",
"tsconfig": "7.0.0",
"tsconfig-paths": "3.11.0",
Expand Down
92 changes: 57 additions & 35 deletions tools/cli/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ import fs from 'fs/promises'
import path from 'path'
import replace from 'replace-in-file'
import sh from 'shelljs'
import type { ReplaceTscAliasPathsOptions } from 'tsc-alias'
import { replaceTscAliasPaths as tsTransformPaths } from 'tsc-alias'
import type { BuildOptions as TsBuildOptions, TsConfig } from 'tsc-prog'
import type { BuildOptions as TsBuildOptions } from 'tsc-prog'
import tsc from 'tsc-prog'
import { loadSync as tsconfigLoad } from 'tsconfig/dist/tsconfig'
import { inspect } from 'util'
Expand All @@ -22,6 +20,8 @@ import { hideBin } from 'yargs/helpers'
import exec from '../helpers/exec'
import logger from '../helpers/logger'
import { $PACKAGE, $WNS, $WORKSPACE } from '../helpers/pkg'
import type { TsRemapOptions } from '../helpers/ts-remap'
import tsRemap from '../helpers/ts-remap'
import tsconfigCascade from '../helpers/tsconfig-cascade'

/**
Expand All @@ -37,56 +37,77 @@ export type BuildOptions = {
*/
dryRun?: boolean

/** @see BuildOptions.dryRun */
d?: BuildOptions['dryRun']

/**
* Name of build environment.
*
* @default 'production'
*/
env?: 'development' | 'production' | 'test'

/** @see BuildOptions.env */
e?: BuildOptions['env']

/**
* Specify module build formats.
*
* @default ['cjs','esm','types']
*/
formats?: ('cjs' | 'esm' | 'types')[]

/** @see BuildOptions.formats */
f?: BuildOptions['formats']

/**
* Run preliminary `yarn install` if package contains build scripts.
*
* @default false
*/
install?: boolean

/** @see BuildOptions.install */
i?: BuildOptions['install']

/**
* Create tarball at specified path.
*
* @default '%s-%v.tgz'
*/
out?: string

/** @see BuildOptions.out */
o?: BuildOptions['out']

/**
* Run `prepack` script.
*
* @default false
*/
prepack?: boolean

/** @see BuildOptions.prepack */
p?: BuildOptions['prepack']

/**
* Pack the project once build is complete.
*
* @default false
*/
tarball?: boolean

/** @see BuildOptions.tarball */
t?: BuildOptions['tarball']
}

export type BuildArgs = Argv<BuildOptions>
export type BuildArgv = Exclude<BuildArgs['argv'], Promise<any>>

export type BuildModuleFormatOptions = {
alias: ReplaceTscAliasPathsOptions
build: TsBuildOptions
trext: TrextOptions<'js', 'cjs' | 'mjs'>
remap: TsRemapOptions
}

/** @property {string[]} BUILD_FORMATS - Module build formats */
Expand Down Expand Up @@ -155,7 +176,7 @@ const args = yargs(hideBin(process.argv), CWD)
.wrap(98) as BuildArgs

const argv: BuildArgv = await args.argv
const { dryRun, env, formats = [], tarball } = argv
const { dryRun = false, env, formats = [], tarball } = argv

// Log workflow start
logger(
Expand Down Expand Up @@ -183,42 +204,43 @@ try {
// See: https://github.com/justkey007/tsc-alias#usage
// See: https://github.com/jeremyben/tsc-prog
// See: https://github.com/flex-development/trext
const options: BuildModuleFormatOptions = {
alias: {
configFile: `tsconfig.prod.${format}.json`,
outDir: `./${format}`,
silent: false
},
build: {
...((): TsConfig => {
const { compilerOptions = {}, exclude = [] } = tsconfigCascade([
[PWD, 'json'],
[PWD, 'prod.json'],
[PWD, suffix]
])

return {
compilerOptions,
exclude,
include: tsconfigLoad(PWD, 'tsconfig.prod.json').config.include
}
})(),
basePath: CWD,
clean: { outDir: true }
},
trext: {
babel: { sourceMaps: 'inline' as const },
from: 'js',
pattern: /.js$/,
to: `${format === 'cjs' ? 'c' : 'm'}js`
const options: BuildModuleFormatOptions = (() => {
const tsconfig = (() => {
const { compilerOptions = {}, exclude = [] } = tsconfigCascade([
[PWD, 'json'],
[CWD, 'json'],
[PWD, 'prod.json'],
[PWD, suffix]
])

return {
compilerOptions,
exclude,
include: tsconfigLoad(PWD, 'tsconfig.prod.json').config.include
}
})()

return {
build: { ...tsconfig, basePath: CWD, clean: { outDir: true } },
remap: {
compilerOptions: { ...tsconfig.compilerOptions, baseUrl: '../..' },
dryRun,
verbose: true
},
trext: {
babel: { sourceMaps: 'inline' as const },
from: 'js',
pattern: /.js$/,
to: `${format === 'cjs' ? 'c' : 'm'}js`
}
}
}
})()

// Build project
!dryRun && tsc.build(options.build)

// Transform paths
!dryRun && tsTransformPaths(options.alias)
tsRemap(options.remap)
dryRun && logger(argv, `build ${format}`)

if (format !== 'types') {
Expand Down
132 changes: 132 additions & 0 deletions tools/helpers/ts-remap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import LogLevel from '@flex-development/log/enums/log-level.enum'
import path from 'path'
import replace from 'replace-in-file'
import { applyChanges } from 'resolve-tspaths/dist/steps/applyChanges'
import { computeAliases } from 'resolve-tspaths/dist/steps/computeAliases'
import { generateChanges } from 'resolve-tspaths/dist/steps/generateChanges'
import { getFilesToProcess } from 'resolve-tspaths/dist/steps/getFilesToProcess'
import type { Alias, Change, ProgramPaths } from 'resolve-tspaths/dist/types'
import { TSConfigPropertyError } from 'resolve-tspaths/dist/utils/errors'
import { TsConfig } from 'tsc-prog'
import { inspect } from 'util'
import logger from './logger'

/**
* @file Helpers - tsRemap
* @module tools/helpers/tsRemap
*/

export type TsRemapOptions = {
/**
* TypeScript compiler options.
*/
compilerOptions: TsConfig['compilerOptions']

/**
* Current working directory.
*
* @default process.cwd()
*/
cwd?: string

/**
* Do **not** emit any file changes.
*/
dryRun?: boolean

/**
* List of file extensions in `tsconfig.outDir` that should be processed.
*
* @default 'js,d.ts'
*/
ext?: string

/**
* Location of source directory (relative to `cwd`).
*
* @default 'src'
*/
src?: string

/**
* Print verbose logs to the console.
*/
verbose?: boolean
}

export type TsRemapResult = {
aliases: Alias[]
changes: Change[]
paths: Pick<ProgramPaths, 'basePath' | 'outPath' | 'srcPath'>
}

/**
* Replaces `options.compilerOptions.paths` with relative paths.
*
* @param {TsRemapOptions} options - Transformation options
* @return {TsRemapResult | null} Result object or null
* @throws {Error}
*/
const tsRemap = (options: TsRemapOptions): TsRemapResult | null => {
// Get transformation options
const {
compilerOptions = {},
dryRun,
cwd = process.cwd(),
ext = 'js,d.ts',
src = 'src',
verbose
} = options

// Handle missing properties
if (!compilerOptions.baseUrl) {
throw new TSConfigPropertyError('resolvePaths', 'compilerOptions.baseUrl')
} else if (!compilerOptions.outDir) {
throw new TSConfigPropertyError('resolvePaths', 'compilerOptions.outDir')
}

// Get program paths
const basePath = path.resolve(cwd, compilerOptions.baseUrl)
const outPath = path.resolve(compilerOptions.outDir)
const srcPath = path.resolve(cwd, src)

// Get path aliases
const aliases = computeAliases(basePath, { compilerOptions })

// Get files to process
const files = getFilesToProcess(outPath, ext)

// Generate path transformations
const changes = generateChanges(files, aliases, { outPath, srcPath })
const $changes = `${changes.length} file${changes.length === 1 ? '' : 's'}`
logger({}, `found ${$changes} using compilerOptions.paths`, [], LogLevel.INFO)

// Log changes
if (verbose) {
for (const change of changes) {
const changes = [inspect(change.changes, false, null)]
logger({}, ` ${change.file}`, changes, LogLevel.DEBUG)
}
}

// Apply path transformations
if (!dryRun) {
applyChanges(changes)

replace.sync({
files: `${outPath}/**/*`,
from: new RegExp(`(../.*)?${process.env.NODE_MODULES}/`),
to: ''
})

if (changes.length > 0) logger({}, 'resolve compilerOptions.paths')
}

return {
aliases,
changes,
paths: { basePath, outPath, srcPath }
}
}

export default tsRemap
Loading

0 comments on commit 78d512a

Please sign in to comment.