Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: normalize typescript lib path for rollup #366

Merged
merged 3 commits into from
Aug 14, 2024
Merged

Conversation

qwqcode
Copy link
Contributor

@qwqcode qwqcode commented Aug 9, 2024

本 PR 补充修复 #360 中新增的 getTsLibFolder 函数在 Win 环境下出现不符合预期的问题。

预期结果 (末尾不包含 /lib/typescript.js):

'node_modules/.pnpm/[email protected]/node_modules/typescript'

错误结果

'node_modules/.pnpm/[email protected]/node_modules/typescript/lib/typescript.js'

在 Windows 环境下,由于路径分隔符斜杠和 Unix 环境不同,require.resolve('typescript') 返回结果需要做 normalizePath 处理,这样才能始终正确地 replace 去掉末尾的 /lib/typescript.js

#360 (comment)

SegaraRai added a commit to SegaraRai/vite-plugin-modular-tailwindcss that referenced this pull request Aug 13, 2024
@qmhc
Copy link
Owner

qmhc commented Sep 6, 2024

我注意到,我们或许可以用 local-pkg 包的 getPackageInfoSync 方法替换当前的这种处理方式。

@qwqcode
Copy link
Contributor Author

qwqcode commented Sep 6, 2024

我注意到,我们或许可以用 local-pkg 包的 getPackageInfoSync 方法替换当前的这种处理方式。

我浏览了下代码,观察到 local-pkg 依赖了 mlly 的 resolvePathSync 函数,而 mlly 的函数又依赖了 import-meta-resolve 这个垫片,考虑可以直接使用它。

import.meta.resolve 函数(ESM 环境的)目前仍然是实验性功能(Node v22.8.0 带 --experimental-import-meta-resolve 参数启用),垫片可以帮助向下兼容旧版 Node 环境。

目前 vite-plugin-dts 里面有 createRequire(import.meta.url).resolve('typescript') 这段代码,它的行为是:

在 ESM 环境使用 createRequire 函数模拟 CommonJS 的 require,然后调用 require.resolve 方法,得到这段代码运行环境中 typescript 这个依赖包在 node_modules 下的目录路径。

考虑到 require.resolve 的缺陷是无法处理一个项目中的 ESM 部分(因为它是基于 CommonJS 的),例如:

const esmPath = require.resolve('./esm-module.mjs'); // 会报错

const esmPath2 = require.resolve('xxx');
// 可能会报错,
// 如果 xxx 这个依赖的 package.json 只有 {"name": "xxx", "type": "module", "main": "src/xxx.mjs"},
// 仅适配了 ESM 环境,而没有适配 CommonJS.

而使用垫片就能很好的解决这个问题,同时兼容支持处理 CommonJS、ESM 项目。

目前,我们调用 resolve 函数输入值是 typescript,而 typescript 项目是同时兼容两种环境的,所以模拟 CommonJS 调用 require.resolve 方法应该也没有问题。

未来等时机成熟可以考虑替换到直接使用原生的 import.meta.resolve.


浏览这些项目发现它们包含很多单元测试,另外我也注意到 import-meta-resolve 与 Node 的标准实现有些差异。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants