NestJS执行build命令时未加载TypeScript格式Webpack配置文件
NestJS + Webpack 使用DefinePlugin注入全局变量失效问题
场景说明
使用Node.js结合NestJS、Webpack构建项目,尝试通过webpack.DefinePlugin注入全局环境变量,但构建后变量未被替换。将Webpack配置文件从TypeScript格式改为JavaScript格式后功能恢复正常,最终确认NestJS会忽略TypeScript格式的Webpack配置文件。
相关配置文件内容
nest-cli.json
{ "$schema": "https://json.schemastore.org/nest-cli", "collection": "@nestjs/schematics", "sourceRoot": "src", "compilerOptions": { "webpack": true, "webpackConfigPath": "./webpack.config.ts" } }
webpack.config.ts
import webpack from 'webpack'; import WebpackShellPluginNext from 'webpack-shell-plugin-next'; import isCI from 'is-ci'; const isDev = process.env.NODE_ENV === 'development' && !isCI; const cliApiDomain = isDev ? 'localhost' : 'xxx.xxx'; const cliApiUrl = isDev ? 'http://localhost:5000' : 'https://www.xxx.xxx'; const dashboardUrl = isDev ? 'http://localhost:8080' : 'https://xxx.xxxx'; const configuration = (options: webpack.Configuration): webpack.Configuration => ({ ...options, plugins: [ ...options.plugins!, new WebpackShellPluginNext({ onBuildStart: { scripts: ['rimraf dist'], blocking: true, }, safe: true, }), new webpack.DefinePlugin({ __CLI_API_DOMAIN__: `'${cliApiDomain}'`, __CLI_API_URL__: `'${cliApiUrl}'`, __DASHBOARD_URL__: `'${dashboardUrl}'`, }), ], }); export default configuration;
package.json 构建脚本
... "build": "nest build", "build:dev": "cross-env NODE_ENV=development nest build", ...
源码中使用全局变量
private config: IConfig = { API_URL: __CLI_API_URL__, DASHBOARD_URL: __DASHBOARD_URL__, };
问题现象
执行构建后,编译产物中__CLI_API_URL__、__DASHBOARD_URL__等变量未被替换,仍以原变量名存在,说明NestJS未加载指定的TypeScript格式Webpack配置文件。
验证结果
将webpack.config.ts改为逻辑完全一致的webpack.config.js后,DefinePlugin正常生效,全局变量被正确替换为对应的值。
内容的提问来源于stack exchange,提问作者Tal Rofe
相关产品推荐
相关产品推荐

