NextJS+TypeScript项目使用TypeDI装饰器编译报错如何解决?
适配SWC的解决方案
你可以完全不用引入Babel,直接通过Next.js内置的SWC配置实现装饰器与元数据支持,操作步骤如下:
- 保留
tsconfig.json中的原有装饰器配置
{ "compilerOptions": { // 其他原有配置不变 "experimentalDecorators": true, "emitDecoratorMetadata": true } }
- 安装SWC官方维护的元数据转换插件
# npm npm install @swc/plugin-transform-typescript-metadata --save-dev # pnpm pnpm add @swc/plugin-transform-typescript-metadata -D # yarn yarn add @swc/plugin-transform-typescript-metadata -D
- 修改项目根目录的
next.config.js配置
/** @type {import('next').NextConfig} */ const nextConfig = { compiler: { // 开启SWC原生装饰器支持,自动兼容legacy模式与class属性loose配置 decorators: true }, experimental: { // 加载元数据转换插件,满足TypeDI依赖注入的元数据读取要求 swcPlugins: [ ["@swc/plugin-transform-typescript-metadata", {}] ] } } module.exports = nextConfig
- 生效配置
删除项目根目录下的.next缓存文件夹,再重启开发服务即可。如果之前项目中添加过.babelrc/babel.config.js等Babel配置文件,请直接删除,Next.js检测到Babel配置会自动降级使用Babel编译,无法启用SWC优化。
内容的提问来源于stack exchange,提问作者Tim Griffiths
相关产品推荐
相关产品推荐

