webpack vue-router延迟加载

时间:2017-10-03 17:55:51

标签: webpack vue.js lazy-loading vue-router

从vue-router documentation开始 延迟加载组件我使用语法:

const Foo = () => import('./Foo.vue')

我有错误:

    client?cd17:49 ./src/routes.js
Module build failed: SyntaxError: Unexpected token (5:19)

  3 | 
  4 | //const User = () => System.import('./components/user/User.vue');
> 5 | const User = () => import('./components/user/User.vue')
    |                    ^
  6 | const UserStart = () => System.import('./components/user/UserStart.vue');
  7 | const UserDetail = () => System.import('./components/user/UserDetail.vue');
  8 | const UserEdit = () => System.import('./components/user/UserEdit.vue');

BabelLoaderError: SyntaxError: Unexpected token (5:19)

  3 | 
  4 | //const User = () => System.import('./components/user/User.vue');
> 5 | const User = () => import('./components/user/User.vue')
    |                    ^
  6 | const UserStart = () => System.import('./components/user/UserStart.vue');
  7 | const UserDetail = () => System.import('./components/user/UserDetail.vue');
  8 | const UserEdit = () => System.import('./components/user/UserEdit.vue');

    at transpile (/app/node_modules/babel-loader/lib/index.js:61:13)
    at Object.module.exports (/app/node_modules/babel-loader/lib/index.js:163:20)
 @ ./src/main.js 4:0-34
 @ multi main
errors @ client?cd17:49
sock.onmessage @ client?cd17:83
EventTarget.dispatchEvent @ eventtarget.js?3e89:51
(anonymous) @ main.js?45b8:274
SockJS._transportMessage @ main.js?45b8:272
EventEmitter.emit @ emitter.js?927b:50
WebSocketTransport.ws.onmessage @ websocket.js?c17e:35

之后我安装了

npm install --save-dev babel-preset-stage-2

npm install --save-dev babel-plugin-transform-export-extensions

还将.babelrc文件配置为:

{
  "presets": [
    ["es2015", { "modules": false }],
    "stage-2"
  ],
  "plugins": [
    "transform-export-extensions"
  ]
}

没有什么有用的,我如何使用这个const Foo = () => import('./Foo.vue')语法来懒散加载组件和webpack和vue-router?

1 个答案:

答案 0 :(得分:2)

安装所需的babel插件:

npm install --save-dev babel-plugin-syntax-dynamic-import

在项目根目录中创建.babelrc,并在文件中包含以下简短代码:

{
    "plugins": ["syntax-dynamic-import"]
}

使用这种方式导入后:

const Foo =()=> import('./ Foo.vue')

最后运行npm build(vue-cli)或npm run watch(laravel)