我的 Vue2 项目是用 Vue CLI 搭建的,使用的 @vue/cli-service 是 4.5.x 版本。
最近在项目中引入了 mermaid 搭建流程图,但是引入依赖启动项目后报错:
Module parse failed: Unexpected token (239:72)
2024-07-02 14:59:36 You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
2024-07-02 14:59:36 | const hasKatex = (text) => {
2024-07-02 14:59:36 | var _a;
2024-07-02 14:59:36 > return (((_a = text.match(katexRegex)) == null ? void 0 : _a.length) ?? 0) > 0;
2024-07-02 14:59:36 | };
2024-07-02 14:59:36 | const calculateMathMLDimensions = async (text, config2) => {
2024-07-02 14:59:36
2024-07-02 14:59:36 @ ./node_modules/.pnpm/mermaid@10.9.1/node_modules/mermaid/dist/mermaid.core.mjs 2:0-42 12:0-14:2
研究过后,发现是 ?? 操作符不兼容,这个可以用 babel 配置解决。
先安装依赖:
pnpm add -D @babel/plugin-proposal-nullish-coalescing-operator @babel/plugin-proposal-optional-chaining
接着修改 babel 配置,plugins 加上这俩:
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
],
plugins: [
'@babel/plugin-proposal-optional-chaining',
'@babel/plugin-proposal-nullish-coalescing-operator'
]
}
最后修改 vue.config.js,将 mermaid 加入到 transpileDependencies
transpileDependencies: ['mermaid'],
重新启动项目就不会报错了