Daniel W.
Daniel W.

Reputation: 32260

Cannot import Vue: SyntaxError: Unexpected identifier

npm install vue --save

Stuff gets installed and stored in package.json and package-lock.json, including:

"vue": "^2.5.21",   
"vue-router": "^3.0.2",
"vue-server-renderer": "^2.5.21",

But when I run

node src/main.js

with sourcecode (this is the full main.js file, 1 line)

import Vue from 'vue';

I get the error

src/main.js:1
(function (exports, require, module, __filename, __dirname) { import Vue from 'vue'
                                                                     ^^^

SyntaxError: Unexpected identifier

The import line is used in many Hello worlds, something simple must be wrong. Node version is v10.15.0. For example https://v2.vuejs.org/v2/guide/components-registration.html

Upvotes: 0

Views: 5683

Answers (1)

Styx
Styx

Reputation: 10076

NodeJS supports CommonJS (require/module.exports) modules only, not ES6 (import/export) you were trying to use.

Those examples you're referring to probable mention using babel transpiler. Under the hood it converts using ES6 modules to CommonJS ones, so node could work.

For example, you can create your test project like this:

npm -g i vue-cli
vue init webpack-simple vue-test-project
cd vue-test-project
npm i
npm run dev

This will install Babel transpiler, Webpack bundler and other needed packages. After that you can use ES6 modules as long as you run npm run dev (to run) or npm run build (to build).

Useful link to read: Vue.js → Installation


This is an answer on "Why import doesn't work?" question. As @DecadeMoon has pointed, vue is not supposed to be run in node.

Upvotes: 2

Related Questions