user3142695
user3142695

Reputation: 17352

JS: Correct require syntax instead using import

Normaly I'm using ES6 syntax to import things from another file:

target.js

import { articles } from '/imports/fixtures.js'

console.log(articles.main)

fixtures.js

export const
  articles = {
    main: { _id: '1234', title: 'anything' }
  }

Now I need to use the fixtures.js file in some testing modules, which needs the require syntax.

But this would not work:

var { articles } = require('/imports/fixtures.js')

What is the correct syntax for this?

Upvotes: 1

Views: 102

Answers (2)

Rahul Kant
Rahul Kant

Reputation: 33

if you are exporting articles as a single object, you need to receive as a single object.

For This

export const
  articles = {
    main: { _id: '1234', title: 'anything' }
  }

Use This

var articles = require('/imports/fixtures.js');

For main This will open the articles object and take out main and store it in a variable main in target.js.

var {main} = require('/imports/fixtures.js');

Upvotes: 0

Ulysse BN
Ulysse BN

Reputation: 11403

Destructuring assignement is a recent feature, if your version of javascript (I guess of nodejs) is prior to ES2015, you could use:

var articles = require('/imports/fixtures.js').articles

N.B: NodeJS supports of desctructuring assignment start with v6.

Upvotes: 2

Related Questions