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

如何用webpack devserver代理静态文件,将static/dist映射到根路径/

调整publicPath配置

首先统一开发、生产环境的publicPath前缀规则,避免两套路径逻辑冲突:

let publicPath;
if (process.env.NODE_BUILD_DEPLOYMENT_PATH) {
    // 生产/预渲染场景取部署路径,直接配置为`/static/dist`即可
    publicPath = process.env.NODE_BUILD_DEPLOYMENT_PATH;
} else {
    // 开发环境也统一添加/static/dist前缀,和预渲染后的资源引用规则对齐
    publicPath = 'http://localhost:8099/static/dist/';
}

配置开发服务器代理

按照你使用的构建工具选择对应配置即可实现路径转发:

Webpack DevServer 配置

在webpack配置文件的devServer字段中添加代理规则:

module.exports = {
  // 其他webpack配置项
  devServer: {
    port: 8099,
    proxy: {
      '/static/dist': {
        target: 'http://localhost:8099',
        pathRewrite: {'^/static/dist' : ''},
        changeOrigin: true
      }
    }
  }
}

Vite 配置

在vite.config.js的server字段中添加代理规则:

export default defineConfig({
  // 其他vite配置项
  server: {
    port: 8099,
    proxy: {
      '/static/dist': {
        target: 'http://localhost:8099',
        rewrite: (path) => path.replace(/^\/static\/dist/, ''),
        changeOrigin: true
      }
    }
  }
})

配置完成后重启开发服务即可生效,所有/static/dist/xxx格式的请求会自动转发到/xxx,完全匹配你需要的static/dist/js转/js的需求,开发阶段不需要修改任何资源引用逻辑,和生产预渲染的路径规则完全对齐。

内容的提问来源于stack exchange,提问作者Ivan Blohin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:15:03