1
votes

As from the vue-router documentation to lazy load components I am using syntax:

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

I have the error:

    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

After that I have installed

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

and

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

also configured .babelrc file to:

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

Nothing helps, how can I use this const Foo = () => import('./Foo.vue') syntax to load components lazily with webpack and vue-router?

1
You are doing async way so particular method could not be just importing component on assignment. This might help you - vuejsdevelopers.com/2017/07/03/vue-js-code-splitting-webpackMeet Zaveri
What version of webpack do you use?Quoc-Anh Nguyen

1 Answers

4
votes

Install required babel plugin:

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

Create .babelrc in your project root, include bellow short code in file:

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

after you can import with this way :

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

finaly run npm build(vue-cli) or npm run watch(laravel)