cnf
2025-05-10 386fa0eca75ddc88165f9b73038f2a2239e1072e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
const path = require('path')
 
const getDependency = err => err.dependencies && err.dependencies.length && err.dependencies[0]
 
const LOCAL_RESOURCE_REGEX = /Module parse failed:\s*(.*)\s*Unexpected character/
 
const LINENO_REGEX = /\(([0-9]+):[0-9]+\)/
 
const FILE_REGEX = /in\s(.*)\s\(line\s([0-9]+),\scolumn\s[0-9]+\)/
 
function formatMessage (msg) {
  if (msg) {
    const matches = msg.match(FILE_REGEX)
    if (matches && matches.length === 3) {
      const filePath = path.relative(process.env.UNI_INPUT_DIR, path.resolve(matches[1]))
      msg = msg.replace(matches[0], 'at ' + filePath.split('?')[0] + ':' + matches[2])
    }
    return msg.replace('Module build failed: ', '模块编译失败:')
  }
  return ''
}
 
const installPreprocessorTips = {}
 
const isMacArm = process.platform === 'darwin' && process.arch === 'arm64'
if (process.env.UNI_SASS_IMPLEMENTATION_NAME === 'dart-sass') {
  let timeout
  const originalStderrWrite = process.stderr.write
  process.stderr.write = function (chunk, encoding, callback) {
    if (typeof chunk === 'string' && chunk.includes('More info and automated migrator')) {
      clearTimeout(timeout)
      timeout = setTimeout(() => {
        console.error(formatDartSassMessage(chunk))
      }, 10)
    }
    return originalStderrWrite.apply(process.stderr, arguments)
  }
}
 
function formatDartSassError (message) {
  const msgs = []
  const syntaxMsgs = []
  // 识别 /deep/ 语法
  if (message.includes('/deep/')) {
    syntaxMsgs.push('将深度选择器 /deep/ 调整为 ::v-deep')
  }
  // 识别除法
  if (message.includes('Using / for division is deprecated')) {
    syntaxMsgs.push('将除法修改为 math.div()')
  }
  const address = 'https://uniapp.dcloud.net.cn/tutorial/syntax-css.html#css-preprocessor'
  const syntaxMsg = syntaxMsgs.length ? `,${syntaxMsgs.join(';')}` : ''
  msgs.push(
    `方案1:调整为 dart-sass 支持的语法${syntaxMsg},详情:${address}`
  )
  msgs.push(
    `方案2:如果您希望继续使用node-sass,${isMacArm ? '需要更换为 HBuilderX Mac Intel 版本,并且' : '您可以'}在 manifest.json 中配置 "sassImplementationName": "node-sass",详情:${address}`
  )
  return msgs.join('\n')
}
 
function formatDartSassMessage (message) {
  const lineBreak = '\n  \n'
  const dartSassMsg = formatDartSassError(message)
  return `${lineBreak}Vue2 scss 预编译器默认已由 node-sass 更换为 dart-sass,如果您的代码使用了 dart-sass 不支持的旧语法,可能存在部分不兼容的问题。
解决方案:
${dartSassMsg}${lineBreak}`
}
 
function ModuleBuildError (err) {
  if (process.env.UNI_SASS_IMPLEMENTATION_NAME === 'dart-sass') {
    if (err.message.includes('SassError:')) {
      err.message = formatDartSassMessage(err.message) + err.message
    }
  }
  const lines = err.message.split('\n')
  let firstLineMessage = lines[0]
  if (lines.length > 1) {
    firstLineMessage = lines[1]
  }
  if (~firstLineMessage.indexOf('Module build failed: ModuleBuildError: Module build failed:')) {
    // 移除调用栈错误
    return false
  }
  if (~firstLineMessage.indexOf('Failed to find')) { // css 引用路径错误
    return {
      line: 1,
      message: '文件查找失败:' + firstLineMessage.split('Failed to find')[1]
    }
  } else if (~firstLineMessage.indexOf('SyntaxError:') || ~firstLineMessage.indexOf('Syntax Error')) {
    if (~firstLineMessage.indexOf('ModuleBuildError: Module build failed: Syntax Error')) {
      return false
    }
 
    if (err.error && err.error.loc) { // babel
      let message = (err.message + '\n').replace('SyntaxError:', '语法错误:')
      message = message.replace(/^\s*at\s.*:\d+:\d+[\s)]*\n/gm, '') + '     '
      return {
        line: err.error.loc.line || 1,
        message
      }
    } else { // css
      let message = (err.message).replace('Syntax Error', '语法错误:')
      message = message.replace(/^\s*at\s.*:\d+:\d+[\s)]*\n/gm, '') + '      '
      const matches = message.match(LINENO_REGEX)
      if (matches && matches.length === 2) {
        return {
          line: matches[1],
          message
        }
      }
    }
  } else if (~err.message.indexOf('Cannot find module')) {
    let builtinCompile = ''
    let name = ''
    if (~err.message.indexOf('compile-less')) {
      name = 'compile-less'
      builtinCompile = 'less'
    } else if (~err.message.indexOf('compile-node-sass')) {
      name = 'compile-node-sass'
      builtinCompile = 'scss/sass'
    } else if (~err.message.indexOf('compile-dart-sass')) {
      name = 'compile-dart-sass'
      builtinCompile = 'scss/sass'
    } else if (~err.message.indexOf('compile-stylus')) {
      name = 'compile-stylus'
      builtinCompile = 'stylus'
    } else if (~err.message.indexOf('compile-typescript')) {
      name = 'compile-typescript'
      builtinCompile = 'typescript'
    } else if (~err.message.indexOf('compile-pug-cli')) {
      name = 'compile-pug-cli'
      builtinCompile = 'pug/jade'
    }
    if (builtinCompile) {
      if (installPreprocessorTips[name]) {
        return false
      }
      installPreprocessorTips[name] = true
      installHBuilderXPlugin(name)
      return {
        message: '预编译器错误:代码使用了' + builtinCompile +
          '语言,但未安装相应的编译器插件,' + (supportAutoInstallPlugin() ? '正在从' : '请前往') +
          '插件市场安装该插件:\nhttps://ext.dcloud.net.cn/plugin?name=' +
          name
      }
    }
  } else if (~firstLineMessage.indexOf('Module parse failed')) {
    const matches = firstLineMessage.match(LOCAL_RESOURCE_REGEX)
    if (matches && matches.length === 2) {
      return {
        message: '资源引用失败:暂不支持引用本地资源\'' + matches[1].trim() + '\',可更换为网络地址或base64'
      }
    }
  }
  return formatMessage(err.message)
}
 
function supportAutoInstallPlugin () {
  // 只要有 HBuilderX 版本号,就一定支持自动安装
  return !!process.env.HX_Version
}
 
function installHBuilderXPlugin (lang) {
  if (supportAutoInstallPlugin()) {
    return console.error(
      `%HXRunUniAPPPluginName%${lang}%HXRunUniAPPPluginName%`
    )
  }
}
 
function ModuleNotFoundError (err) {
  const matches = err.message.match(/Can't resolve '(.*loader)'/)
  if (matches && matches.length > 0) {
    return {
      line: 1,
      message: `
Failed to resolve loader: ${matches[1]}
You may need to install it.
`
    }
  }
  const dependency = getDependency(err)
  if (dependency) {
    let line = 1
    if (dependency.loc.start && dependency.loc.start.line) {
      line = dependency.loc.start.line
    }
    return {
      line: line,
      message: '文件查找失败:\'' + dependency.userRequest + '\''
    }
  }
}
 
function ModuleParseError (err) {
  const firstLineMessage = err.message.split('\n')[0]
  const matches = firstLineMessage.match(LOCAL_RESOURCE_REGEX)
  if (matches && matches.length === 2) {
    return {
      message: `资源引用失败:暂不支持引用此类型资源(${err.module.rawRequest})`
    }
  }
}
 
module.exports = {
  ModuleBuildError,
  ModuleNotFoundError,
  ModuleParseError
  // ChunkRenderError(err) {},
  // EntryModuleNotFoundError(err) {},
  // ModuleDependencyError(err) {},
  // ModuleError(err) {},
  // ModuleDependencyWarning(warn) {},
  // ModuleWarning(warn) {}
}