您的位置:首页 > 产品设计 > UI/UE

vue-router 按需加载

2017-11-02 16:10 309 查看
vue的单页面(SPA)项目,必然涉及路由按需的问题。
以前我们是这么做的

//require.ensure是webpack里面的,这样做会将单独拉出来作为一个chunk文件
const Login = r => require.ensure( [], () => r (require('../component/Login.vue')));


但现在无Vue-router的官网看看,推荐这种方式:

//vue异步组件和webpack的【代码分块点】功能结合,实现了按需加载
const App = () => import('../component/Login.vue');


可是,很多情况下,我们这么写npm控制台直接报错,这是为什么呢?

Module build failed: SyntaxError: Unexpected token


原来是import这儿报错了,这就需要babel的插件了,vue-router官网上有一段提示:
如果您使用的是 Babel,你将需要添加 syntax-dynamic-import 插件,才能使 Babel 可以正确地解析语法。
至此,问题全部解决了。

如果使用vue-cli生成项目,很可能在babel-loader没有配置上面的插件,这时需要我们自己去安装此插件:

cnpm install babel-plugin-syntax-dymic-import --save-dev


然后修改js的loader部分:

{
test: /\.js$/,
loader:'babel-loader',
options:{
plugins:['syntax-dynamic-import']
},
},


  

增加了option选项,至此,能识别我们const App = () => import('../component/Login.vue');的语法了,页面出来了:



在打包的时候,发现我们如果只是这么写:const App = () => import('../component/Login.vue');出现的chunk包名字都是乱的,如果我们指定命名,该怎么办呢?webpack3提供了Magic Comments(魔法注释)

const App = () => import(/* webpackChunkName:'login'*/ '../component/Login.vue');


 这样我们就为打包出来的chunk指定一个名字,最终生成login.js的chunk包。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: