在Nestjs Workspaces单体仓库模式下使用nestjs-seeder遇编译问题
NestJS Monorepo 中 nestjs-seeder 无法编译执行的解决方案
问题根源
你之前将 seeder.ts 配置为 assets 是错误的——assets 用于复制静态资源(如 JSON、HTML 文件),不会对 TypeScript 文件进行编译转译,因此编译后不会生成对应的 seeder.js 文件。以下是三种可行的解决方案:
方案一:关闭 Webpack 编译(适合无需 Webpack 的场景)
Webpack 默认只会打包入口文件(main.ts),关闭后 TypeScript 编译器会编译所有符合配置的文件:
- 修改根目录
nest-cli.json,关闭全局 Webpack 配置:
{ "$schema": "https://json.schemastore.org/nest-cli", "collection": "@nestjs/schematics", "sourceRoot": "apps/api/src", "compilerOptions": { "deleteOutDir": true, "webpack": false, // 关闭 Webpack "tsConfigPath": "apps/api/tsconfig.app.json" }, "monorepo": true, "root": "apps/api", "projects": { "api": { "type": "application", "root": "apps/api", "entryFile": "main", "sourceRoot": "apps/api/src", "compilerOptions": { "tsConfigPath": "apps/api/tsconfig.app.json" } }, "users": { "type": "application", "root": "apps/users", "sourceRoot": "apps/users/src", "compilerOptions": { "tsConfigPath": "apps/users/tsconfig.app.json" // 移除原有的 assets 配置 } }, "auth": { "type": "library", "root": "libs/auth", "entryFile": "index", "sourceRoot": "libs/auth/src", "compilerOptions": { "tsConfigPath": "libs/auth/tsconfig.lib.json" } } } }
- 确保
apps/users/tsconfig.app.json包含所有需要编译的文件:
{ "extends": "../../tsconfig.json", "compilerOptions": { "outDir": "../../dist/apps/users", "module": "commonjs", "types": ["node"] }, "include": ["src/**/*"], "exclude": ["node_modules", "dist", "test", "**/*spec.ts"] }
- 编译并执行:
nest build users node dist/apps/users/seeder.js
方案二:保留 Webpack,配置多入口编译
如果必须使用 Webpack,需为 users 应用配置多入口,让 seeder.ts 也被打包:
- 在
apps/users目录下创建webpack.config.js:
const webpack = require('webpack'); const path = require('path'); const nodeExternals = require('webpack-node-externals'); const { RunScriptWebpackPlugin } = require('run-script-webpack-plugin'); module.exports = function (options, webpack) { return { ...options, entry: { main: './src/main.ts', seeder: './src/seeder.ts' // 添加 seeder 入口 }, output: { ...options.output, filename: '[name].js' // 按入口名生成对应文件 }, externals: [nodeExternals()], plugins: [ ...options.plugins, new RunScriptWebpackPlugin({ name: 'main.js' }) // 仅自动运行主入口 ], }; };
- 修改
nest-cli.json中users项目的配置,指定自定义 Webpack 配置:
"users": { "type": "application", "root": "apps/users", "sourceRoot": "apps/users/src", "compilerOptions": { "tsConfigPath": "apps/users/tsconfig.app.json", "webpack": true, "webpackConfigPath": "apps/users/webpack.config.js" } }
- 编译并执行:
nest build users node dist/apps/users/seeder.js
方案三:直接用 ts-node 运行(无需提前编译)
跳过编译步骤,直接用 ts-node 执行 seeder.ts:
npx ts-node apps/users/src/seeder.ts
也可以在项目根目录的 package.json 中添加脚本简化操作:
{ "scripts": { "seed:users": "ts-node apps/users/src/seeder.ts" } }
执行时只需运行:
npm run seed:users
内容的提问来源于stack exchange,提问作者EL MAHDI BOUZKOURA
相关产品推荐
相关产品推荐

