Vite在AWS CodeBuild构建失败:无法找到SVG模块及类型声明
解决AWS CDK Pipeline中Vite React项目构建的TS2307错误
核心问题分析
错误TS2307: Cannot find module './assets/react.svg' or its corresponding type declarations是因为TypeScript默认不识别SVG等非代码模块,而Vite对静态资源的处理需要配套的类型声明来让TS编译器认可。同时你的CDK Pipeline命令存在目录切换逻辑错误,也可能加剧问题。
具体解决步骤
1. 正确配置SVG类型声明
在Vite项目的src目录下,找到vite-env.d.ts(如果没有则新建),添加以下类型声明:
// 适配两种导入方式:直接导入路径或React组件式导入 declare module '*.svg' { import React = require('react'); export const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>; const src: string; export default src; }
然后检查tsconfig.json的include字段,确保包含该声明文件:
{ "compilerOptions": { /* 现有配置 */ }, "include": ["src/**/*", "src/vite-env.d.ts"], "references": [{ "path": "./tsconfig.node.json" }] }
不要手动修改@types文件夹,Vite项目的类型声明应该放在项目源码目录内,由TS自动识别。
2. 修正CDK Pipeline的构建命令
你的Synth步骤命令存在目录错误:执行npx cdk synth时应该回到CDK基础设施代码所在的目录(而非前端项目目录),同时primaryOutputDirectory应该指向CDK生成的cdk.out目录(而非前端的dist)。
假设你的项目结构是:
仓库根目录/ ├── frontend/ # Vite初始化的前端项目 └── infra/ # AWS CDK基础设施代码(或CDK代码在根目录)
调整后的Synth步骤代码:
const pipeline = new CodePipeline(this, "CahmFrontendPipeline", { pipelineName: "CahmFrontendPipeline", synth: new ShellStep("Synth", { input: CodePipelineSource.gitHub("myuser/myrepo", "master", { authentication: cdk.SecretValue.secretsManager("MY_SECRET"), }), // CDK Synth的输出目录是cdk.out,而非前端的dist primaryOutputDirectory: "cdk.out", commands: [ // 构建前端项目 "cd frontend", "npm install", "npm run build", // 回到根目录,执行CDK Synth(如果CDK代码在根目录) "cd ..", "npm install", "npx cdk synth", // 如果CDK代码在infra目录,替换为: // "cd ../infra", // "npm install", // "npx cdk synth" ], }), });
3. 确认CodeBuild镜像环境
使用AWS CodeBuild的标准Node.js镜像,比如aws/codebuild/amazonlinux2-x86_64-standard:5.0,该镜像预装了Node.js 18、npm等工具,完全兼容Vite和CDK的构建需求。无需自定义镜像。
验证步骤
- 本地执行前端构建命令
cd frontend && npm run build,确认无TS错误 - 本地执行CDK Synth命令,确认生成
cdk.out目录 - 重新触发Pipeline构建,检查CodeBuild日志是否消除错误
内容的提问来源于stack exchange,提问作者Dan Ruxton
相关产品推荐
相关产品推荐

