Bug记录——Cannot read property ‘replace’ of undefined

Cannot read property ‘replace’ of undefined

今天开始用最新的vue-cli创建项目的时候,选择自定义配置项目,结果构建完项目,开始 vue add element-plus 的时候给我报了错,给了我源码错误,百思不得其解,然后开始分析这段源码

  api.afterInvoke(() => {
    const { EOL } = require('os')
    const fs = require('fs')
    const contentMain = fs.readFileSync(api.resolve(api.entryFile), { encoding: 'utf-8' })
    const lines = contentMain.split(/\r?\n/g)

    const renderIndex = lines.findIndex(line => line.match(/createApp\(App\)(\.use\(\w*\))*\.mount\(['"]#app['"]\)/))
    const renderContent = lines[renderIndex]
    lines[renderIndex] = `const app = createApp(App)`
    lines[renderIndex + 1] = `installElementPlus(app)`
    lines[renderIndex + 2]  = renderContent.replace('createApp\(App\)','app')

    fs.writeFileSync(api.resolve(api.entryFile), lines.join(EOL), { encoding: 'utf-8' })
  })

这是我更改完之后的源代码。

然后可以发现这不就是main.jscreateApp(App).use(store).use(router).mount("#app");的正则格式化语法嘛,我发现vue自动配置mount("#app"),仔细看是双引号,而element-plus官方这个api是单引号,我服了,难道不测试不同配置下的情况嘛,只能说这波和vue配合的不是很好,网上这个错误不好找,所以得到一个道理,遇见啥错误直接看源码。

不知道是不是官方小伙独爱单引号, 麻烦修改一下正则吧

最后附上fix code的详细

// ./node_modules/vue-cli-plugin-element-plus/generator/index.js:45:45 bug fix
// edit line 41
// error code
    const renderIndex = lines.findIndex(line => line.match(/createApp\(App\)(\.use\(\w*\))*\.mount\('#app'\)/))
// fix code
    const renderIndex = lines.findIndex(line => line.match(/createApp\(App\)(\.use\(\w*\))*\.mount\(['"]#app['"]\)/))

以上转自DarkForestTheory的原文


以下是咸鱼居士——卷饼侠的脑瘫错误:
之后又报错了一次

// main.js
createApp(App)
    .use(router)
    .mount('#app')

在学上面的老哥看源码后,
以下是修改后的代码

// main.js
createApp(App).use(router).mount('#app')

成功运行~

posted @   卷饼侠  阅读(698)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示