Nuxt 2项目兼容JS与TS配置及插件注入报错排查
问题
我有一个100%基于JavaScript的Nuxt 2.17.2项目,需要接入若干纯TypeScript编写的SDK,希望配置项目以同时运行JavaScript与TypeScript,且不影响现有代码。
按照官方TypeScript指南操作后,尝试通过plugins注入一个.ts后缀的简单函数进行测试,现有配置如下:
src/plugins/myInjectedFunction.ts
import Vue from 'vue' declare module 'vue/types/vue' { interface Vue { $myInjectedFunction(message: string): void } } Vue.prototype.$myInjectedFunction = (message: string) => console.log(message)
myInjectedFunctionTest.vue
<template> <div> <button @click="$myInjectedFunction('Test')">Click me !</button> </div> </template> <script lang="ts"> import { defineComponent } from 'vue' export default defineComponent({ mounted () { this.$myInjectedFunction('works in mounted') } }) </script>
vue-shim.d.ts
declare module "*.vue" { import Vue from 'vue' export default Vue }
tsconfig.json
{ "compilerOptions": { "target": "ES2018", "module": "ESNext", "moduleResolution": "Node", "lib": [ "ESNext", "ESNext.AsyncIterable", "DOM" ], "esModuleInterop": true, "allowJs": true, "sourceMap": true, "strict": true, "noEmit": true, "baseUrl": ".", "paths": { "~/*": [ "./*" ], "@/*": [ "./*" ] }, "types": [ "@nuxt/types", "@nuxt/typescript-build", "@types/node" ] }, "exclude": [ "node_modules" ] }
运行项目时出现如下错误:
TypeError: this.$myInjectedFunction is not a function at VueComponent.mounted (myInjectedFunction.vue:6:1) at invokeWithErrorHandling (vue.runtime.esm.js:3017:1) at callHook$1 (vue.runtime.esm.js:4032:1) at Object.insert (vue.runtime.esm.js:4427:1) at invokeInsertHook (vue.runtime.esm.js:6946:1) at Vue.patch [as __patch__] (vue.runtime.esm.js:7094:1) at Vue._update (vue.runtime.esm.js:3765:1) at Vue.updateComponent (vue.runtime.esm.js:3868:1) at Watcher.get (vue.runtime.esm.js:3446:1) at new Watcher (vue.runtime.esm.js:3436:1)
请问我遗漏了什么或操作有误?
解决方案
出现这个错误的核心原因是你没有在Nuxt配置中注册这个TypeScript插件,导致插件代码根本没被执行,所以Vue.prototype上没有挂载对应的方法。
按以下步骤修正:
- 修改
nuxt.config.js(或nuxt.config.ts),在plugins数组中添加你的TypeScript插件路径:
export default { // ...其他配置 plugins: [ // 插件在src目录下,路径写成'~/plugins/myInjectedFunction.ts' '~/plugins/myInjectedFunction.ts' ] }
- 确保安装了必要依赖:
如果还没安装,执行以下命令:
npm install --save-dev @nuxt/typescript-build typescript vue-property-decorator # 或用yarn yarn add --dev @nuxt/typescript-build typescript vue-property-decorator
- 验证配置:
重启Nuxt服务后,点击测试页面的按钮,控制台会输出对应日志,mounted钩子中的调用也会正常执行。
额外注意事项:
- 项目根目录没有
nuxt.config.ts的话,用nuxt.config.js即可,Nuxt 2会自动识别并处理TypeScript插件。 - 保持
tsconfig.json中的allowJs: true,原有JS代码不会受影响。 - 类型声明部分(
declare module 'vue/types/vue')无需修改,它仅为TypeScript提供类型提示,不影响代码运行。
内容的提问来源于stack exchange,提问作者Falcon Stakepool
相关产品推荐
相关产品推荐

