Nuxt2.6.2+TS+Koa2.7.0运行dev命令时Vue文件TS语法编译报错问询
Nuxt 2.6.2 + TypeScript + Koa 2.7.0 编译Vue文件TS语法报错解决方案
该报错的核心原因是:通过Koa启动Nuxt作为中间件时,Nuxt不会自动加载TypeScript相关的编译处理规则,仅通过babel-node处理了服务端Koa代码的编译,未配置Vue文件内TS语法、装饰器语法的解析规则。直接运行nuxt命令时Nuxt会自动加载对应规则,因此不会报错。
步骤1:安装缺失依赖
安装TS编译、装饰器解析所需的依赖:
yarn add @nuxt/typescript-build ts-loader @babel/preset-typescript @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties -D
步骤2:修改nuxt.config.js配置
显式添加TS构建模块、装饰器解析规则:
module.exports = { // 关闭nuxt遥测询问,避免弹出Are you interested in participating?提示 telemetry: false, // 原有其他配置保持不变 buildModules: [ '@nuxt/typescript-build' ], build: { babel: { presets: ['@babel/preset-env', '@babel/preset-typescript'], plugins: [ ['@babel/plugin-proposal-decorators', { legacy: true }], ['@babel/plugin-proposal-class-properties', { loose: true }] ] }, extend(config, { isDev }) { // 识别ts后缀文件 config.resolve.extensions.push('.ts') // 配置ts-loader处理Vue文件内的TS代码 config.module.rules.push({ test: /\.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, options: { appendTsSuffixTo: [/\.vue$/], transpileOnly: isDev } }) } } }
步骤3:配置根目录tsconfig.json
添加TS语法支持规则,开启装饰器支持:
{ "compilerOptions": { "target": "esnext", "module": "esnext", "strict": true, "moduleResolution": "node", "experimentalDecorators": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "sourceMap": true, "baseUrl": ".", "paths": { "~/*": ["./*"], "@/*": ["./*"] }, "lib": ["esnext", "dom"] }, "include": ["**/*.ts", "**/*.d.ts", "**/*.vue", "server/**/*.ts"], "exclude": ["node_modules"] }
步骤4:修改package.json启动命令
给babel-node添加TS预设,支持服务端TS代码编译:
{ "scripts": { "dev": "cross-env NODE_ENV=development nodemon server/index.ts --watch server --exec babel-node --presets @babel/preset-env,@babel/preset-typescript" } }
完成以上配置后重新执行yarn dev即可正常编译。
内容的提问来源于stack exchange,提问作者EdenSheng
相关产品推荐
相关产品推荐

