3

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?

Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
Travis Heeter
  • 13,002
  • 13
  • 87
  • 129

2 Answers2

7

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 */ })
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
5

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';
Wadu
  • 107
  • 1
  • 12
  • This is not a good idea if you're intending to use tree-shaking, as it will load the entire Vue object instead of just what you need. [Documentation](https://v3.vuejs.org/guide/migration/global-api-treeshaking.html#internal-helpers) – snumpy Aug 27 '21 at 21:03