NX最新版本代理配置问题:project.json与proxyConfig.js失效
最新版本NX配置代理的有效方法
针对你遇到的旧代理配置失效问题,以下是适配最新NX版本的解决方案:
1. 确认Executor版本
首先检查project.json中的serve executor是否已更新为最新的@nx/web:dev-server(旧版@nrwl/web:dev-server在新NX版本中已被弃用):
"serve": { "executor": "@nx/web:dev-server", "defaultConfiguration": "local", // ... 其他原有配置 }
2. 方案一:Webpack项目代理配置
如果你的项目基于Webpack,可通过以下两种方式配置代理:
方式A:集成到Webpack配置文件
- 修改
project.json的local配置,替换原proxyConfig为webpackConfig:
"local": { "buildTarget": "comp:build:local", "hmr": true, "webpackConfig": "apps/comp/webpack.config.js" }
- 在
webpack.config.js中添加代理逻辑:
const { composePlugins, withNx } = require('@nx/webpack'); module.exports = composePlugins(withNx(), (config) => { // 覆盖或扩展devServer配置 config.devServer = { ...config.devServer, proxy: { '/nedit': { target: 'http://localhost:4200/edit', secure: false, logLevel: 'debug', onProxyRes: function (proxyRes, req, res) { proxyRes.headers['Cross-Origin-Opener-Policy'] = 'same-origin'; proxyRes.headers['Cross-Origin-Embedder-Policy'] = 'require-corp'; }, }, }, }; return config; });
方式B:保留独立proxyConfig.js文件
若想继续使用原proxyConfig.js,可在Webpack配置中导入它:
const { composePlugins, withNx } = require('@nx/webpack'); const PROXY_CONFIG = require('./proxyConfig.js'); module.exports = composePlugins(withNx(), (config) => { config.devServer = { ...config.devServer, proxy: PROXY_CONFIG, }; return config; });
3. 方案二:Vite项目代理配置
如果你的项目使用Vite(最新NX默认推荐),需在vite.config.ts中配置代理:
import { defineConfig } from 'vite'; import nx from '@nx/vite/plugins/nx'; export default defineConfig({ plugins: [nx()], server: { proxy: { '/nedit': { target: 'http://localhost:4200/edit', secure: false, logLevel: 'debug', configure: (proxy) => { proxy.on('proxyRes', (proxyRes) => { proxyRes.headers['Cross-Origin-Opener-Policy'] = 'same-origin'; proxyRes.headers['Cross-Origin-Embedder-Policy'] = 'require-corp'; }); }, }, }, }, });
验证配置
启动本地服务后,通过控制台日志(因设置logLevel: 'debug'会输出代理详情)或浏览器开发者工具的网络请求,确认请求是否被正确转发到目标地址。
内容的提问来源于stack exchange,提问作者henskjold73
相关产品推荐
相关产品推荐

