Following documentation I cannot create an instance of Vue.js 3

Viewed 1533

The code

https://stackblitz.com/edit/vue-ttt?file=src/main.js

The Problem

I'm trying to build a simple tic-tac-toe app in StackBlitz. This is my main.js file:

import Vue from "vue";
import App from "./App.vue";
import TicTacToe from "./components/TicTacToe";
import Cell from "./components/Cell";

Vue.component("tic-tac-toe", TicTacToe);  // error: "cannot read property 'component' of undefined"

Also note my package.json file has vue as a dependency:

"dependencies": {
  "vue": "^3.0.0"
},

So the error means Vue needs to be defined, ok so I refer to the 3x documentation:

const app = Vue.createApp({ /* options */ })

But I get Cannot read property 'createApp' of undefined


So then I try to define an instance:

const Vue = new Vue({});

I get Cannot access 'Vue' before initialization


So, based on a google search of that error, I try:

Vue = new Vue({})

And I get vue_1.default is not a constructor.

So what am I doing wrong?

2 Answers

When you work with bundler like vue-cli, webpack or vite ..., you should import createApp to create new instance and use it for app.use or app.component ... :

 import { createApp } from "vue";
 const app = createApp({ /* options */ })

Using CDN like :

<script src="https://unpkg.com/vue@next"></script>

the Vue instance is available globally so you could use it as follows :

const app = Vue.createApp({ /* options */ })

You are getting this error because Vue3 is using named export instead of a default export. You can read more about it here.

You can fix this error by simply importing all the named exports onto an object called Vue:

import * as Vue from 'vue';
Related