Next.js项目本地测试通过,GitHub Actions中SVG导入测试失败求助
解决GitHub Actions中Next.js测试TS2307 SVG模块找不到的问题
1. 补全SVG类型声明并确保被TS识别
- 在项目根目录或
src目录下新建types/svg.d.ts文件,写入以下内容:
declare module '*.svg' { import type { ReactElement, SVGProps } from 'react'; const content: (props: SVGProps<SVGElement>) => ReactElement; export default content; }
- 打开
tsconfig.json,检查include字段,确保包含这个类型声明文件,比如:
{ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "types/**/*.d.ts"] }
如果类型文件放在src/types下,记得对应调整路径。
2. 确保依赖安装无遗漏
- 检查
package-lock.json是否已提交到仓库,npm ci会严格按照这个文件安装依赖,本地新增的依赖或类型包如果没提交,CI环境会缺失。确认@types/react、@types/node这类TS相关依赖版本和Next.js兼容。 - 可以在CI流程里加依赖缓存,避免重复安装出问题:
- name: Cache node modules uses: actions/cache@v3 env: cache-name: cache-node-modules with: path: ~/.npm key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} restore-keys: | ${{ runner.os }}-build-${{ env.cache-name }}-
3. 给测试框架配置SVG处理规则
如果用Jest跑测试,需要单独配置SVG的mock,否则测试时不会走Next.js的webpack规则:
- 新建
jest.config.js,添加模块映射:
module.exports = { // 其他配置... moduleNameMapper: { '\\.svg$': '<rootDir>/__mocks__/svgMock.ts', }, };
- 在
__mocks__/svgMock.ts里写mock内容:
export default 'SVG_MOCK';
如果用Next.js自带的next/jest配置,确保正确引入Next的配置:
const nextJest = require('next/jest'); const createJestConfig = nextJest({ dir: './', }); const customJestConfig = { // 其他自定义配置 }; module.exports = createJestConfig(customJestConfig);
4. 锁定TypeScript版本
本地和CI环境的TS版本不一致可能导致解析规则差异,在package.json里锁定TS版本,比如:
{ "devDependencies": { "typescript": "^5.0.0" } }
避免用*或者未锁定版本的写法,确保CI安装的版本和本地一致。
5. 提前执行类型检查
在测试前先跑类型检查,提前发现问题:
- 在
package.json里加脚本:
{ "scripts": { "type-check": "tsc --noEmit" } }
- 在GitHub Actions步骤里添加:
- name: Run TypeScript type check run: npm run type-check
内容的提问来源于stack exchange,提问作者himmip
相关产品推荐
相关产品推荐

