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>
`;
由于vite以
#
角色而挣扎。您可以使用Vite插件在路径中转换
#
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" />;