【问题标题】:Vue.js 3 - "Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html"Vue.js 3 - “加载模块脚本失败:服务器以非 JavaScript MIME 类型“text/html”响应
【发布时间】:2021-04-11 18:32:32
【问题描述】:

我正在 Vue 3 中构建一个网站,所有路线都存储在 routes.json 中。 (我这样做是为了在一个地方更新所有会随着时间而改变的数据。)但是当我尝试 eval() 我的 views 的延迟加载函数时,我收到错误“加载模块失败脚本:服务器以“text/html”的非 JavaScript MIME 类型响应。”在控制台中。下面是router/index.js

import { createRouter, createWebHistory } from 'vue-router'
import routes from '../../data/routes.json'

let evalRoutes = []
for (let i = 0; i < routes.routes.length; i++)
  evalRoutes[i] = routes.routes[i]

for (let i = 0; i < evalRoutes.length; i++)
  evalRoutes[i].component = eval(evalRoutes[i].component)
console.log(evalRoutes)

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes: evalRoutes,
})

export default router

下面是routes.json

{
  "routes": [
    {
      "path": "/",
      "name": "Home",
      "component": "() => import('../views/Home')"
    },
    {
      "path": "/about",
      "name": "About",
      "component": "() => import('../views/About')"
    },
    {
      "path": "/contact",
      "name": "Contact",
      "component": "() => import('../views/Contact')"
    },
    {
      "path": "/policy",
      "name": "Policy",
      "component": "() => import('../views/Policy')"
    }
  ]
}

我以前没有见过任何人这样做,所以如果您知道解决方案,请将其留在下面:)

设置: 我有 Vue 3、Babel、具有历史模式和 SASS 的路由器,仅此而已。

【问题讨论】:

    标签: javascript json vue.js vuejs3


    【解决方案1】:

    这可能是因为您的服务器不支持历史模式。历史模式依赖服务器重写将路由传递给 index.html 文件。

    您需要提供有关您的设置和 Apache 或 nginx 配置的更多信息。以下是文档中的示例设置:example-server-configurations

    或者,您可以通过将createWebHistory 替换为createWebHashHistory 来使用hashbang 模式。此方法依赖于路由中的# 字符,它将处理通过index.html 页面的所有路由,而无需服务器重写。

    【讨论】:

    • 我的服务器确实支持历史模式...我会更新我的问题哎呀
    【解决方案2】:

    我(提问者)已经想通了!为此,我们需要将"component" 设置为null。然后,在index 中,我们不评估每个字符串导入,而是将每个组件设置为具有名称的导入。

    【讨论】:

      猜你喜欢
      • 2020-05-11
      • 2022-08-07
      • 2023-04-01
      • 2021-03-07
      • 2021-06-05
      • 2020-09-10
      • 1970-01-01
      • 2021-01-26
      • 2019-11-08
      相关资源
      最近更新 更多