You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NX 16中React库(Vite)配置Storybook代理失败求助

NX 16中Vite构建的React库Storybook代理配置无效的解决方案

针对NX 16下基于Vite构建的React库中Storybook代理不生效(应用中正常)的问题,可尝试以下几种解决方案:

方案1:通过Storybook的viteFinal钩子配置代理

修改libs/mylib/.storybook/main.js,利用viteFinal钩子直接修改最终的Vite配置,确保代理规则被正确加载:

const config = {
  stories: ['../src/lib/**/*.stories.@(js|jsx|ts|tsx|mdx)'],
  addons: ['@storybook/addon-essentials'],
  framework: {
    name: '@storybook/react-vite',
    options: {
      builder: {
        viteConfigPath: 'libs/actividad/ui/vite.config.ts',
      },
    },
  },
  async viteFinal(viteConfig) {
    // 初始化server配置(避免原有配置为空)
    viteConfig.server = viteConfig.server || {};
    // 添加代理规则
    viteConfig.server.proxy = {
      '/intervi': {
        target: 'http://localhost:9000',
        changeOrigin: true,
      },
    };
    return viteConfig;
  },
};

export default config;

viteFinal是Storybook提供的核心钩子,会在所有Vite配置合并后执行,能确保代理规则覆盖其他配置。

方案2:修正project.json中的代理配置

如果使用proxyConfig指定外部代理文件,需确保路径和文件格式正确:

  1. 确保apps/proxy.conf.json的内容格式正确:
{
  "/intervi": {
    "target": "http://localhost:9000",
    "changeOrigin": true
  }
}
  1. 确认libs/mylib/project.json中proxyConfig的路径相对于工作区根目录:
"storybook": {
  "executor": "@nx/storybook:storybook",
  "options": {
    "port": 4400,
    "proxyConfig": "apps/proxy.conf.json",
    "configDir": "libs/actividad/ui/.storybook"
  }
}

修改后完全重启Storybook服务,热重载不会加载新的代理配置。

方案3:检查Vite配置文件的正确性

确保libs/mylib/vite.config.ts的导出格式正确,且路径被Storybook正确识别:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/intervi': {
        target: 'http://localhost:9000',
        changeOrigin: true,
      },
    },
  },
});

同时确认main.js中viteConfigPath的路径无误,避免因路径错误导致配置未被加载。

额外注意事项

  • 修改代理配置后必须完全重启Storybook,代理规则仅在服务启动时初始化。
  • 查看浏览器控制台的网络请求,确认请求路径是否匹配代理规则,排查是否存在路径拼写错误。
  • 若NX缓存导致配置未更新,执行nx reset清除缓存后再启动服务。

内容的提问来源于stack exchange,提问作者Hans Poo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 05:07:10