0

I have a file with 3 objects, and I want to import each object in a different file.

const object1 {

s1: {
title: "placeholder title",
description: "placeholder description"
   }
}
const object2 {

s1: {
title: "placeholder title",
description: "placeholder description"
   }
}
const object3 {

s1: {
title: "placeholder title",
description: "placeholder description"
   }
}

To export them I am using this code -

module.exports = { object1, object2, object3 }

and in my separate file to import them

import object1 from "../data";
import object2 from "../data";
import object3 from "../data";

I can see in my console logs that this doesn't load each object separately, it loads them as one big object.

How do I export/import this correctly?

4
  • Can you add what your console log returns when you try to load? Thanks! Commented Aug 23, 2020 at 17:35
  • Sure - console.log(object1) returns - Object { object1: {…}, object2: {…}, object3: {…} } and console.log(object2) or object3 returns the same Commented Aug 23, 2020 at 17:41
  • 1
    Thanks! My guess is you're exporting all modules as one object. Can you try exporting them separately like this: module.exports.object1 = object1;. Otherwise you can also, parse your import object into separate object by doing this: importedObjectVariable.object1 and so on. Commented Aug 23, 2020 at 17:50
  • 1
    You need to use the same import and export syntax in both modules. Either use export object1 and then import object1 from "../data"; or use module.exports = { object1, object2, object3 } and const {object1} = require('../data');. Don't try to mix and match CommonJS module syntax with ESM module syntax. While, it can be done in some circumstances, it's not easy to do it right. And, if using ESM syntax, make sure the loader knows you're using an ESM module. Commented Aug 23, 2020 at 18:01

1 Answer 1

1

Since you added the ecamscript-6 tag you can export the consts individually like this:

export const object1 {

s1: {
title: "placeholder title",
description: "placeholder description"
   }
}
export const object3 {

s1: {
title: "placeholder title",
description: "placeholder description"
   }
}
export const object3 {

s1: {
title: "placeholder title",
description: "placeholder description"
   }
}

Then in a different file you can import one of the objects like this:

import { object1 } from '../data.js';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.