Skip to content

Commit

Permalink
fix(plugin-compiler): 修复异步 require 或 require.async 的参数被跳过解析可能引起运行时报错的…
Browse files Browse the repository at this point in the history
…问题 (#66)
  • Loading branch information
lyfeyaj authored Jun 28, 2023
1 parent 48eee25 commit 50f29b7
Showing 1 changed file with 17 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ import path from 'path'
export class DynamicRequireSupportPlugin implements Plugin {
name = 'DynamicRequireSupportPlugin'
apply(runner: Runner<any>) {
const warnDynamicRequire = function (
const warnDynamicRequireAndProcessRestExpression = function (
parser: webpack.javascript.JavascriptParser,
expressions: any,
requireType: string
) {
const fileName = parser?.state?.module?.nameForCondition?.() || ''
Expand All @@ -24,6 +25,9 @@ export class DynamicRequireSupportPlugin implements Plugin {
)} 中包含异步 ${requireType},将跳过静态解析,请自行保证引用路径的正确`
)
}

// 让 webpack 继续处理函数的参数,确保后续参数中的代码可以被正确处理
if (expressions) parser.walkExpressions(expressions)
}
// require('filepath', callback) 支持
const parseDynamicRequire = (
Expand Down Expand Up @@ -53,7 +57,11 @@ export class DynamicRequireSupportPlugin implements Plugin {
continue
}

warnDynamicRequire(parser, 'require')
warnDynamicRequireAndProcessRestExpression(
parser,
expression.arguments,
'require'
)

return true
}
Expand All @@ -68,11 +76,17 @@ export class DynamicRequireSupportPlugin implements Plugin {
expression.type === 'CallExpression' &&
calleeMembers?.includes?.('async')
) {
warnDynamicRequire(parser, 'require.async')
warnDynamicRequireAndProcessRestExpression(
parser,
expression.arguments,
'require.async'
)

return true
}
})
}

runner.hooks.compiler.tap(this.name, (compiler) => {
compiler.hooks.normalModuleFactory.tap(this.name, (factory) => {
factory.hooks.parser
Expand Down

0 comments on commit 50f29b7

Please sign in to comment.