I am not able to use dynamic imports in vue router - vue.js

I am developing a web page in vuejs and I am using webpack 4 and babel 6 for compiling the assets
When i put something like... route('home', '/', () => import('../pages/home.vue')) the compiler says me Support for the experimental syntax 'dynamicImport' isn't currently enabled and I cant use that syntax
I need help, thanks
This is my package.json:
https://gist.github.com/sarmanulco/fd2415c2b81db3df457302c61d77f197

To use vue-router with lazy-loading component:
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'homepage',
component: () => import('#/pages/Home.vue') //lazy loading
},
]
})
Make sure you take a look at vue-router docs

To use the dynamicImport add a .babelrc file (where the package.json is located)
Here is the content of the .babelrc:
{
"plugins": ["#babel/plugin-syntax-dynamic-import"]
}

Related

<router-view> not working even though its connected

I am a newbie when it comes to vue. So I followed this tutorial
https://www.youtube.com/watch?v=WLQDpY7lOLg&ab_channel=TheCodeholic . In which I am in the "adding view router" section.
I did what all the changes and add on's he made (from creating the views folder & components and creating the router folder and its inside index.js and even the imports) yet when I try to npm run dev, there is nothing on my website.
here is my code from the router folder:
import {createRouter , createWebHistory} from 'vue-router'
import Dashboard from "../views/Dashboard.vue"
import Login from "../views/Login.vue"
import Register from "../views/Register.vue"
const routes = [
{
path: '/',
name: 'Dashboard',
component: Dashboard
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/register',
name: 'Register',
component: Register
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
a code from my views/Dashboard.vue
<template>
<h1> Dashboard </h1>
</template>
<script>
export default {
name: 'Dashboard'
}
</script>
<style scoped>
</style>
and from my main.js
import { createApp } from 'vue'
import './style.css'
import store from './store'
import router from './router'
import './index.css'
import App from './App.vue'
createApp(App).mount('#app')
createApp(App).use(store)
createApp(App).use(router)
Here is a photo of when I run npm run dev
enter image description here
I can't seem to see what is wrong even though I checked up multiple times. Please help :<
here is what I expected to actually happen
enter image description here
Error looks to be here
createApp(App).mount('#app')
createApp(App).use(store)
createApp(App).use(router)
mount() should go last. From the Vue docs:
The .mount() method should always be called after all app configurations and asset registrations are done.
You can also optionally chain everything together like so:
createApp(App).use(store).use(router).mount('#app')
Which if you're using typescript, can then actually catch your error in your IDE beforehand

How can I redirect using vue-router?

I have tried to access to others pages via url, but those pages never loads
http://localhost:8080/index
http://localhost:8080/about
This is my main.js file
import Vue from 'vue'
import App from './App.vue'
import vuetify from './plugins/vuetify';
import VueRouter from 'vue-router'
Vue.config.productionTip = false
Vue.use(VueRouter)
import Index from './views/Index';
const About = { template: '<p>about page</p>' }
const routes = [
{ path: '/index', name: 'index', component: Index },
{ path: '/about', name: 'about', component: About }
]
var router = new VueRouter({
routes: routes,
mode: 'history'
})
new Vue({
router: router,
vuetify,
render: h => h(App)
}).$mount('#app')
Does anyone can help me with vue-router? i am new in this framework
Does it work if you access them like this:
http://localhost:8080/#/about
If yes, your vue-router is working in the default hash-mode. To get rid of the hash and get "normal" URLs you'll need to set it to history mode.
Edit:
As I see you're already using history mode. Do you use Vue CLI for local development? This should normally work out of the box. If not, you need to setup some redirect rules on other web servers. Please see the examples here: Example Server Configurations
Edit 2:
Can you show your App component?
I tried to reproduce your problem in a sandbox, but it works: https://codesandbox.io/s/confident-voice-zyg07
The App component here looks like this, including the router-view:
<template>
<div id="app">
<router-view id="page"/>
</div>
</template>
<script>
export default {
name: "App",
components: {}
};
</script>

Should I add Babel in order to use Webpack?

According to a post I’ve read:
Babel’s plugin-syntax-dynamic-import is essential to be able to use lazy loading. Otherwise webpack will not compile this syntax const AppHome= () => import("#/components/AppHome");
In addition, I can’t see Webpack option when I start a new project using vue-cli. I see only Babel.
Does it mean that Babel is mandatory if I want to use Webpack in my Vue project?
Is there any alternative if I want to use lazy loading and Webpack?
I don't think I understand something, if you use vue-cli you have built-in webpack, babel, lazy-loading components and many other libraries.
I checked vue-cli 2.5.2 as the first edge code, and everything works as it should loads chunks.
import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
// lazy load pages
const lazyLoad = view => () =>
import ( /* webpackChunkName: "chunk-" */ `#/pages/${view}`);
export default new Router({
mode: 'history',
routes: [{
path: '/',
name: 'Home',
component: lazyLoad('Home')
},
{
path: '/form',
name: 'Form',
component: lazyLoad('Form')
}
]
});

Nested routes not rendering in router-view

I'm setting up what is going to be a large system, so I want to have decentralised router.js files for every module. Each of them would have routes arrays declarations that would be pushed to the main routes array.
So for now I have a kind of root of routes file, which have the VueRouter instances and settings, and it imports the first level of route.js files to build the routes array.
main routes.js file
import DashboardRoutes from './views/dashboard/routes'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{// Root public site
path: '/',
component: () => import('./views/pages/Index'),
children: PagesRoutes
},
name: 'page_error',
path: '*',
component: () => import('./views/error/Error')
}
].concat(
DashboardRoutes
)
})
module (first level) routes.js file
import InventoryRoutes from './inventarios/routes'
const routes = {
path: '/panel',
component: () => import('./Index'), // This Index has a layout with a router-view in it
children: [
// Inicio del panel
{
name: 'dashboard',
path: '',
component: () => import('./Dashboard'),
}
].concat(
InventariosRoutes
)
}
export default routes
Components (second level) routes.js file
const routes = {
path: 'inventario',
name: 'panel_inventario',
component: { template: '<router-view/>' },
children: [
// Productos y servicios
{
name: 'panel_inventarios_productos-servicios',
path: 'productos-servicios',
component: () => import('./productos-servicios/ProductosServiciosHome'),
},
]
}
export default routes
In the components tree of vue-tools I see an AnnonymousComponent in the place where my children's router-view should be.
Update
I just create an external component to name it and check if it's being rendered like this
Components (second level) routes.js file
const loader = {
template: `
<div class="InventarioLoader">
<router-view></router-view>
</div>
`,
name: 'InventarioLoader'
}
const routes = {
path: 'inventario',
name: 'panel_inventario',
component: loader,
children: [
// children go here
]
}
Now I see my InventarioLoader component, but I still don't see my children components rendered in it
Update
I see this error on the console
You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
By default, Vue does not compile string templates. This is for performance reasons.
Since the runtime-only builds are roughly 30% lighter-weight than their full-build counterparts, you should use it whenever you can
See https://v2.vuejs.org/v2/guide/installation.html#Runtime-Compiler-vs-Runtime-only
Either create a real single-file component or use a render function
import Vue from 'vue'
const RouterView = Vue.component('router-view')
const loader = {
name: 'InventarioLoader',
render (createElement) {
return createElement(RouterView)
}
}
Apparently now you can't point a route to a inline component like {template:'<router-view/>} and my solution was to create a loader component with that template and use it on the parent route

vue components registration and routes

I want to use routing in my vue project, but don't register many components globally, I am having trouble here.
My project uses vue-cli and vue-router
My project idea is to register these subcomponents only in the parent component that uses the corresponding subcomponent, but I want to use routing to control the presentation of these components.
My code is as follows
Main.js
import Vue from "vue";
import App from "./App";
import VueRouter from 'vue-router'
import test from "./components/test.vue"
Vue.use(VueRouter)
Vue.config.productionTip = false;
const routes = [
{
path: '/test', component: test,
}
]
const router = new VueRouter({routes: routes});
new Vue({
router,
render: h => h(App),
}).$mount('#app')
App.vue
<template>
<div>
<main-layout>
<router-view></router-view>
</main-layout>
</div>
</template>
<script>
import MainLayout from "./components/MainLayout.vue"
import test from "./components/test.vue"
export default {
components: {
"main-layout": MainLayout,
"test": test
},
name : "app",
data(){
return {
collapsed: false,
}
},
}
</script>
Just like the code above, I have to register every component that needs to be managed by routing in main.js and app.vue. These are cumbersome and the code is not beautiful. Is there any way or plugin to solve this problem?
You can move all the routing code to a different folder (possibly named router).
Inside the folder you can have a file called index.js that builds the router and move individual routing components to different files.
Each router component should only return router information and not a router object.
You'll still need to import individual vue components, but they'll be scattered across multiple files. This should make things tidier.
In your main.js will need to import the router, something similar to this
import router from './router'
....
Vue.use({
router
})
This is a possible folder structure for your router:
This is part of router/index.js that shows how to use routes defined in other files
import Vue from 'vue'
import Router from 'vue-router'
import API from '#/api'
import DashboardRoutes from './dashboard'
import CustomerRoutes from './customer'
import MaintenanceRoutes from './maintenance'
import DashboardStudioRoutes from './studio'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/api',
name: 'Api',
component: Api
},
DashboardStudioRoutes,
DashboardRoutes,
CustomerRoutes,
MaintenanceRoutes,
{
path: '*',
name: '404',
component: NotFound
},
],
scrollBehavior (to, from, savedPosition) {
return { x: 0, y: 0 }
}
})