在 JavaScript 文件中导入 Vue Router 导致 'Module Parse Failed' 错误
Importing Vue Router inside a JavaScript file causes 'Module Parse Failed' Error
我试图在axios的拦截器中访问路由器,但是当我在.js
axios文件中导入文件时,出现错误Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders > <template>
。
这是 router.js 文件的示例:
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
const router = {
base: process.env.BASE_URL,
routes: [
{
path: "/settings",
name: "settings",
component: require('@/views/Settings.vue'),
}
]
};
export default new Router(router);
拦截器文件包含:
import router from './router';
为什么要使用 require('@/views/Settings.vue')
?
尝试使用 import
函数。
import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
const router = {
base: process.env.BASE_URL,
routes: [
{
path: '/settings',
name: 'settings',
component: () => import('@/views/Settings.vue'),
},
],
};
export default new Router(router);
PS: 回答您的评论。
在 main.js
文件中导出实例变量:
import Vue from 'vue';
import App from './App.vue';
import router from './router';
Vue.config.productionTip = false;
let vm = new Vue({
router,
render: h => h(App),
}).$mount('#app');
export default vm; // ATENTION HERE
在 axios.js
文件中导入 main.js
并访问 $router
:
import vm from './main.js';
...
// YOUR INTERCEPTOR
vm.$router.push({ name: 'settings' });
...
我试图在axios的拦截器中访问路由器,但是当我在.js
axios文件中导入文件时,出现错误Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders > <template>
。
这是 router.js 文件的示例:
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
const router = {
base: process.env.BASE_URL,
routes: [
{
path: "/settings",
name: "settings",
component: require('@/views/Settings.vue'),
}
]
};
export default new Router(router);
拦截器文件包含:
import router from './router';
为什么要使用 require('@/views/Settings.vue')
?
尝试使用 import
函数。
import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
const router = {
base: process.env.BASE_URL,
routes: [
{
path: '/settings',
name: 'settings',
component: () => import('@/views/Settings.vue'),
},
],
};
export default new Router(router);
PS: 回答您的评论。
在 main.js
文件中导出实例变量:
import Vue from 'vue';
import App from './App.vue';
import router from './router';
Vue.config.productionTip = false;
let vm = new Vue({
router,
render: h => h(App),
}).$mount('#app');
export default vm; // ATENTION HERE
在 axios.js
文件中导入 main.js
并访问 $router
:
import vm from './main.js';
...
// YOUR INTERCEPTOR
vm.$router.push({ name: 'settings' });
...