简体   繁体   English

vite在请求static html时发送root index.html内容

[英]Vite sends root index.html content when static html is requested

I'm using the charting library from TradingView, which requires static HTML to be loaded inside an iFrame. I've placed the static html inside the public folder:我正在使用 TradingView 的图表库,它需要将 static HTML 加载到 iFrame 中。我已将 static html 放在public文件夹中:

/public/charting_library/en-tv-chart.b555c6a4.html

And it is accessed via:它通过以下方式访问:

localhost:3000/charting_library/en-tv-chart.b555c6a4.html

However, when requesting the above URL, the contents are that of the root index.html , not that of the static asset.但是,当请求上述 URL 时,内容是根index.html的内容,而不是 static 资产的内容。

How can I get Vite to route the HTML asset correctly here?如何让 Vite 在此处正确路由 HTML 资产?

I solved this by using Vite middleware:我通过使用 Vite 中间件解决了这个问题:

function chartingLibrary(): PluginOption {
  return {
    apply: 'serve',
    configureServer(server: ViteDevServer) {
      return () => {
        server.middlewares.use(async (req, res, next) => {
          if (req.originalUrl?.includes('/charting_library/') && req.originalUrl?.includes('html')) {
            res.setHeader('Content-Type', 'text/html');
            res.writeHead(200);
            res.write(fs.readFileSync(path.join(__dirname, `public/${req.originalUrl}`)));
            res.end();
          }

          next();
        });
      };
    },
    name: 'charting-library',
  };
}

And then in the config:然后在配置中:

{
  // ...
  plugins: [
    // ...
    chartingLibrary(),
  ],
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM