Dire Akanbi
Dire Akanbi

Reputation: 21

How do I export an array of objects and it's properties to another JS file?

My ongoing school project entails me to use WebPack, the static module bundler. Now what I'm trying to do is export

const data = [
  {
    description: "Go swimming",
    completed: true,
    index: 1,
  },
  {
    description: "Create an animated puppet",
    completed: false,
    index: 2,
  },
  {
    description: "Hack NASA",
    completed: false,
    index: 2,
  },
];

and import it in my functions.js file with the import function. But it's not working.

Upvotes: 2

Views: 3683

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075347

Webpack supports JavaScript native modules (ESM), which I suggest using. (As opposed to CommonJS [require calls and such].)

You almost literally have the export part in the question, just move the export into the code block:

export const data = [
    // ...
];

That's a named export. You import it like this (if the above is in the-source-module.js in the same directory):

import { data } from "./the-source-module.js";

...with the import function.

There isn't an import function, but there's a very function-like import construct called dynamic import. It looks exactly like a function that returns a promise. If that's what you're being told to use (instead of an import declaration as above), it would look like this:

In an environment that supports top-level await (Webpack does):

const { data } = await import("./the-source-module.js");
// ...use `data` here...

In an environment that doesn't:

import("./the-source-module.js")
.then(({data}) => {
    // ...use `data` here...
})
.catch(error => {
    // ...import failed...
});
// DON'T TRY TO USE `data` HERE, IT WON'T WORK

More on MDN:

I also cover modules in Chapter 13 of my recent book JavaScript: The New Toys (and promises in Chapter 8, and all the other ES2015-ES2020 stuff).


Note: The use of {} in import { data } from ... may look a bit like destructuring, but it isn't destructuring. Other than the {}, but the semantics and syntax of named imports and destructuring are quite different. For instance, if you wanted to use a name other than data, it would be import { data as yourName } from ..., which is not how renaming works with destructuring.

Slightly confusingly, the examples above with dynamic import() are using destructuring. The promise "returned" by import() is fulfilled with an object called a "module namespace object" that has a property for each named export. That along with its dynamic nature is a fundamental difference between dynamic import() and import declarations.

Upvotes: 3

Related Questions