Skip to content

Commit

Permalink
fix: incorrect alias transform if using a regexp that ends with slash
Browse files Browse the repository at this point in the history
fix #290
  • Loading branch information
qmhc committed Dec 25, 2023
1 parent b06d2c4 commit 213aa39
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 17 deletions.
20 changes: 13 additions & 7 deletions examples/vue/vite.config.ts
Expand Up @@ -10,11 +10,17 @@ emptyDir(resolve(__dirname, 'types'))

export default defineConfig({
resolve: {
// alias: [{ find: /^@\/(.+)/, replacement: resolve(__dirname, '$1') }]
alias: {
'@': resolve(__dirname),
'@components': resolve(__dirname, 'src/components')
}
// alias: {
// '@': resolve(__dirname),
// '@components': resolve(__dirname, 'src/components')
// }
alias: [
{
find: /@\//,
replacement: resolve(__dirname) + '/'
},
{ find: '@components', replacement: resolve(__dirname, 'src/components') }
]
},
build: {
lib: {
Expand All @@ -37,9 +43,9 @@ export default defineConfig({
],
// include: ['src/index.ts'],
exclude: ['src/ignore'],
staticImport: true,
// staticImport: true,
// rollupTypes: true,
insertTypesEntry: true,
// insertTypesEntry: true,
compilerOptions: {
declarationMap: true
},
Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -17,6 +17,7 @@
"prettier": "pretty-quick --staged && pnpm run lint",
"release": "tsx scripts/release.ts",
"test": "vitest run",
"test:dev": "vitest",
"test:react": "pnpm -C examples/react build",
"test:svelte": "pnpm -C examples/svelte build",
"test:ts": "pnpm -C examples/ts build",
Expand Down
6 changes: 5 additions & 1 deletion src/plugin.ts
Expand Up @@ -139,7 +139,7 @@ export function dtsPlugin(options: PluginOptions = {}): import('vite').Plugin {
return { find: key, replacement: value }
})
} else {
aliases = ensureArray(aliasOptions)
aliases = ensureArray(aliasOptions as Alias[]).map(alias => ({ ...alias }))
}

if (aliasesExclude.length > 0) {
Expand All @@ -156,6 +156,10 @@ export function dtsPlugin(options: PluginOptions = {}): import('vite').Plugin {
)
)
}

for (const alias of aliases) {
alias.replacement = resolve(alias.replacement)
}
},

async configResolved(config) {
Expand Down
27 changes: 19 additions & 8 deletions src/transform.ts
@@ -1,4 +1,4 @@
import { dirname, isAbsolute, relative } from 'node:path'
import { dirname, isAbsolute, relative, resolve } from 'node:path'

import { isRegExp, normalizePath } from './utils'

Expand Down Expand Up @@ -85,6 +85,10 @@ function isAliasMatch(alias: Alias, importer: string) {
)
}

function ensureStartWithDot(path: string) {
return path.startsWith('.') ? path : `./${path}`
}

const globalImportRE =
/(?:(?:import|export)\s?(?:type)?\s?(?:(?:\{[^;\n]+\})|(?:[^;\n]+))\s?from\s?['"][^;\n]+['"])|(?:import\(['"][^;\n]+?['"]\))/g
const staticImportRE = /(?:import|export)\s?(?:type)?\s?\{?.+\}?\s?from\s?['"](.+)['"]/
Expand Down Expand Up @@ -119,17 +123,24 @@ export function transformAliasImport(
return str
}

const truthPath = isAbsolute(matchedAlias.replacement)
? normalizePath(relative(dirname(filePath), matchedAlias.replacement))
const dir = dirname(filePath)
const replacement = isAbsolute(matchedAlias.replacement)
? normalizePath(relative(dir, matchedAlias.replacement))
: normalizePath(matchedAlias.replacement)

const endSlash = matchResult[1].match(matchedAlias.find)![0].endsWith('/')
const truthPath = matchResult[1].replace(
matchedAlias.find,
replacement + (endSlash ? '/' : '')
)
const normalizedPath = normalizePath(relative(dir, resolve(dir, truthPath)))

// for debug
// console.log(replacement, truthPath, filePath, resolve(dir, truthPath), normalizedPath)

return str.replace(
isDynamic ? simpleDynamicImportRE : simpleStaticImportRE,
`$1'${matchResult[1].replace(
matchedAlias.find,
(truthPath.startsWith('.') ? truthPath : `./${truthPath}`) +
(typeof matchedAlias.find === 'string' && matchedAlias.find.endsWith('/') ? '/' : '')
)}'${isDynamic ? ')' : ''}`
`$1'${ensureStartWithDot(normalizedPath)}'${isDynamic ? ')' : ''}`
)
}
}
Expand Down
14 changes: 13 additions & 1 deletion tests/transform.spec.ts
Expand Up @@ -63,10 +63,18 @@ describe('transform tests', () => {
it('test: transformAliasImport', () => {
const aliases: Alias[] = [
{ find: /^@\/(.+)/, replacement: resolve(__dirname, '../$1') },
{ find: /^@components\/(.+)/, replacement: resolve(__dirname, '../src/components/$1') }
{ find: /^@components\/(.+)/, replacement: resolve(__dirname, '../src/components/$1') },
{ find: /^~\//, replacement: resolve(__dirname, '../src/') }
]
const filePath = resolve(__dirname, '../src/index.ts')

expect(
transformAliasImport(filePath, 'import type { TestBase } from "@/src/test";\n', aliases)
).toEqual("import type { TestBase } from './test';\n")

expect(transformAliasImport(filePath, 'import("@/components/test").Test;\n', aliases)).toEqual(
"import('../components/test').Test;\n"
)
expect(
transformAliasImport(
filePath,
Expand All @@ -86,6 +94,10 @@ describe('transform tests', () => {
aliases
)
).toEqual("import VContainer from './components/layout/container/VContainer.vue';\n")

expect(
transformAliasImport(filePath, 'import type { TestBase } from "~/test";\n', aliases)
).toEqual("import type { TestBase } from './test';\n")
})

it('test: removePureImport', () => {
Expand Down

0 comments on commit 213aa39

Please sign in to comment.