vite dev服务器在公共资产文件名中遇到#处理# 我有一个vitejs+react+tyspript项目,其中包含#字符的文件名,如images/foo#2.png,images/foo#2.png等。 即使

问题描述 投票:0回答:1
images/foo#2.png

等。 开发服务器在解释此路径方面遇到了一些麻烦,即使通过

encodeURIComponent()
#
将其变成
%23
,因此资产无法正确链接到。
我想知道我是否可以使用一些中间件来解决此问题。
显而易见的解决方案是重命名文件,但这在我的控制之外,因为它们在第三方存储库中添加为子模块,并且需要分叉并添加构建步骤 /脚本以将它们重命名为所有文件夹,这不是理想的。
辅助是示例代码复制该问题:
// main.js
document.querySelector('#app').innerHTML = `
  <div>
    <ul>
      vite.svg: <img src="vite.svg" /><br/>
      vite#2.svg with no encodeURIComponent: <img src="vite#2.svg" /><br/>
      vite#2.svg with encodeURIComponent: <img src="${encodeURIComponent(
        'vite#2.svg'
      )}" />
    </ul>
  </div>
`;

Folder Structure 由于vite以Result#角色而挣扎。您可以使用Vite插件在路径中转换

#
javascript reactjs typescript encoding vite
1个回答
0
投票
第一件事在您的项目中创建一个名为vite-plugin-fix-hash.ts的文件,并添加:

export default function fixHashInPaths() { return { name: 'fix-hash-in-paths', // Fix paths during build transform(code, id) { return id.includes('#') ? code.replace(/#/g, '_hash_') : code; }, // Fix requests at runtime configureServer(server) { server.middlewares.use((req, _, next) => { if (req.url?.includes('%23')) req.url = req.url.replace('%23', '_hash_'); next(); }); }, }; }

然后在
vite.config.ts
中,导入并使用插件:

import { defineConfig } from 'vite'; import fixHashInPaths from './vite-plugin-fix-hash'; export default defineConfig({ plugins: [fixHashInPaths()], });

最终更新您的文件路径,例如:
const imagePath = '/images/foo_hash_2.png';  // Use _hash_ instead of #
<img src={imagePath} alt="Fixed Image" />;

	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.