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

Vite生产构建后CSS/JS无法加载问题求助

解决方案

1. 修正Vite配置文件

在vite.config.js中明确设置base为根路径,确保构建后的资源引用路径正确:

export default {
  base: '/'
}

2. 调整资源引用方式

Vite对src目录下的资源有特定处理逻辑,不要在index.html中手动引入src里的CSS和JS:

  • 移除index.html中的<link>和<script>标签(指向src目录资源的部分)
  • 在src/main.js中通过import导入CSS:
    import './style.css'
    

Vite会自动将JS打包并注入到构建后的index.html中,无需手动添加脚本引用。

调整后的index.html仅保留基础结构:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>FindRecipe</title>
</head>
<body>
  <div id="recipe-container"></div>
  <!-- 其他页面结构 -->
</body>
</html>

3. 确保DOM加载完成后执行JS逻辑

找不到recipe-container的问题,是因为JS代码在DOM渲染前就执行了。修改main.js,将逻辑包裹在DOM加载完成的监听事件中:

document.addEventListener('DOMContentLoaded', () => {
  const recipeContainer = document.getElementById('recipe-container');
  if (!recipeContainer) {
    console.error('未找到recipe-container元素');
    return;
  }
  // 所有API调用、DOM操作逻辑放在此处
});

4. 重新构建并验证

执行以下命令重新构建项目:

npm run build

用npm run preview本地预览构建产物,确认资源加载正常后再部署到Netlify。

5. 检查Netlify部署设置

在Netlify项目配置中确认:

  • 构建命令为npm run build
  • 发布目录为dist
  • 无额外路径重写规则干扰资源加载

内容的提问来源于stack exchange,提问作者Joseph Martin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:33:14