Import and Export

Each file of a Vue app is a module: a part of the program with its own variables. What a module creates exists only in that module, so App.vue can't see the variables of another file. A file shares a value by exporting it, and the file that needs the value imports it. You've written import lines since the first lesson. Here's how they work.

A file can have one default export, its main value, written with export default. It's imported without curly braces, under a name that the importing file chooses:

// cafe.js
const menu = [
    { id: 1, name: "Espresso", price: 2 },
    { id: 2, name: "Cappuccino", price: 3 },
];

export default menu;
// App.vue
import menu from "./cafe.js";

A file can also export any number of values under their names, with export in front of const. These named exports are imported in curly braces, under their exact names, separated by commas:

// cafe.js
export const cafeName = "Corner Café";
export const openingHours = "7 am to 7 pm";
// App.vue
import { cafeName, openingHours } from "./cafe.js";

When a file has both, one import can get both: the default export first, then the named ones in braces, import menu, { cafeName } from "./cafe.js";. Braces where there should be none, or the other way round, are a common mistake: the import then doesn't find the value, and the page shows nothing in its place. (In a project on your own computer, the browser stops at such an import instead, with an error that the file “does not provide an export named …”.)

Now you can read every import you've seen:

  • import { ref } from "vue"; imports the named export ref of the package vue. A name without ./ is a package, a library installed in the project.
  • import App from "./App.vue"; in main.js imports the default export of App.vue: the component.
  • import "./style.css"; imports nothing by name. It just adds the stylesheet to the page.

But where's the export in App.vue? You don't write it: <script setup> exports the component for you, as the file's default export. That's why import MenuItem from "./MenuItem.vue"; has no braces. And <script setup> can't have exports of its own; the red bar would say <script setup> cannot contain ES module exports. Values that several components need go into a .js file, such as cafe.js here.

And the extension? Vite, the tool that runs Vue projects on your computer, finds a .js file even without it, but a .vue file only with it. To keep it simple, write it in every import of your own files.

Instructions

  1. Run the code: the heading is empty, and the console says [Vue warn]: Property "cafeName" was accessed during render but is not defined on instance. The values are in cafe.js, which doesn't export them. Export cafeName and openingHours from cafe.js by name, and import both in App.vue with one import.

  2. Make menu the default export of cafe.js: write export default menu; at the end of the file. Import it in App.vue under the name menu. The list shows the whole menu.