Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion packages/taro-platform-h5/src/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,17 @@ export default class H5 extends TaroPlatformWeb {
const viteCompilerContext = await getViteH5CompilerContext(this)
if (viteCompilerContext) {
const exts = Array.from(new Set(viteCompilerContext.frameworkExts.concat(SCRIPT_EXT)))
if (id.startsWith(viteCompilerContext.sourceDir) && exts.some((ext) => id.includes(ext))) {

let cleanId = id

if (cleanId.startsWith('\u0000')) {
cleanId = cleanId.slice(1)
}

cleanId = cleanId.split('?')[0].replace(/\\/g, '/') // 👈 替换斜杠方向

const normalizedSourceDir = viteCompilerContext.sourceDir.replace(/\\/g, '/') // 👈 替换斜杠方向
if (cleanId.startsWith(normalizedSourceDir) && exts.some((ext) => id.includes(ext))) {
Comment on lines +236 to +237
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

避免路径前缀误匹配:建议加“目录边界”判定

当前使用 startsWith 可能将 /src 与 /src2 误判为命中。建议在归一化后为 sourceDir 补尾随斜杠,或计算相对路径/使用边界判断,降低误伤范围。

可考虑最小变更如下:

-              const normalizedSourceDir = viteCompilerContext.sourceDir.replace(/\\/g, '/') // 👈 替换斜杠方向
-              if (cleanId.startsWith(normalizedSourceDir) && exts.some((ext) => id.includes(ext))) {
+              let normalizedSourceDir = viteCompilerContext.sourceDir.replace(/\\/g, '/') // 👈 替换斜杠方向
+              normalizedSourceDir = normalizedSourceDir.replace(/\/+$/, '') + '/'
+              const inSourceDir = cleanId.startsWith(normalizedSourceDir)
+              if (inSourceDir && exts.some((ext) => id.includes(ext))) {
🤖 Prompt for AI Agents
In packages/taro-platform-h5/src/program.ts around lines 236 to 237, the current
use of startsWith to check if cleanId begins with normalizedSourceDir can cause
false positives when paths like <sourceDir>/src2 are mistaken for
<sourceDir>/src. To fix this, ensure normalizedSourceDir ends with a trailing
slash after normalization, then check if cleanId starts with this adjusted path
to enforce directory boundary matching and avoid incorrect matches.

// @TODO 后续考虑使用 SWC 插件的方式实现
const result = await transformAsync(code, {
filename: id,
Expand Down
Loading