Reputation:
I am building a website in Vue 3 with all the routes stored in routes.json
. (I did this so I have one place to update all of the data that will change over time.) But when I try to eval()
the lazy-load functions for my views
, I get the error "Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html"." in the console. Below is 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
And below is 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')"
}
]
}
I haven't seen anyone do this before, so if you know a solution please leave it down below :)
SETUP: I have Vue 3, Babel, Router with history mode and SASS, nothing else.
Upvotes: 10
Views: 11831
Reputation:
I (the question asker) have figured it out! To do such things, we need to set "component"
to null. Then, in index
, instead of evaluating each string import, we set each component to the import with the name.
Upvotes: -3
Reputation: 35684
This is likely because your server does not support history mode. History mode relies on the server rewrite to pass the routes to index.html file.
You will need to provide more information regarding your setup and your Apache or nginx configuration. Here is the sample setups from the docs: example-server-configurations
Alternatively, you can use the hashbang mode by replacing createWebHistory
with createWebHashHistory
. This method relies on the #
character in the route, which will process all routes through the index.html page without server rewrites.
Upvotes: 3