vue.jsimportexport

How to export and import js files?


I have exported a variable from the navbar.js file:

export const navbar = {
  bunch of code
}

I would like to import it into the main.js file:

import { createApp } from 'vue'
import { navbar } from './navbar.js';

const navApp = createApp({})

navApp.component('navbar',navbar);

navApp.mount('#nav-app')

I made sure that the HTML script is type = "module"

<script src="https://unpkg.com/vue@3/dist/vue.global.js" defer></script>
<script type = "module" src="./js/vuejs/main.js" defer></script>

I am getting this error:

Uncaught TypeError: Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../

Is there something I might be missing.

PS: the reason I am doing it this way is that the main.js file will be managing the components that are in different js files.

Please also let me know if you have any suggestions for a better way of managing files.


Solution

  • Modify the main.js file: Instead of importing Vue from "vue", import it from the CDN:

    import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';
    import { navbar } from './navbar.js';
    
     const navApp = createApp({});
     navApp.component('navbar', navbar);
     navApp.mount('#nav-app');