Import ES6 modules with properties

407
March 12, 2017, at 12:18 PM

I am using ES6 on the server with NodeJS. I use babel to transpile it and everything works correctly, but I have a problem where I do not know how to proceed. I need to be able to write this fragment of code ES5 in code ES6, I would appreciate someone explaining how to do it and why it does not work what I am doing.

In particular, I need to make this code in ES5, run in ES6:

const mailgun = require('mailgun-js')({
  apiKey: config.mail.api.api_key,
  domain: config.mail.api.domain
})

Currently, I am trying to use the following code, but it does not work:

import mailgun from 'mailgun-js'
mailgun = {
  apiKey: config.mail.api.api_key,
  domain: config.mail.api.domain
}

The configuration parameters have a config.js file which works correctly. When transpiling the code, the console returns me the following error message in the log:

Log Message

I need to know what the error is in using that syntax, and what would be the correct way to do this. Thank you.

Answer 1

You can change your ES5 to this:

const mailgun = require('mailgun-js');
const your_var = mailgun({
  apiKey: config.mail.api.api_key,
  domain: config.mail.api.domain
});

In ES6, this would be:

import mailgun from 'mailgun-js';
const your_var = mailgun({
  apiKey: config.mail.api.api_key,
  domain: config.mail.api.domain
});
Answer 2

The previous code is doing this:

  1. Requiring mailgun-js
  2. Calling the result as a function, passing in some config
  3. Taking the result of that as mailgun

To do the same in ES6, if we assume that the function is the default export, first we import the function, then we call it:

import mailgunFactory from 'mailgun-js';
const mailgun = mailgunFactory({
  apiKey: config.mail.api.api_key,
  domain: config.mail.api.domain
});
Rent Charter Buses Company
READ ALSO
javascript push value into array using for loop [on hold]

javascript push value into array using for loop [on hold]

I have a array A and I want to add values that I got from a for loop:

441
How to: REST API that passes and array of key/value pairs

How to: REST API that passes and array of key/value pairs

I am looking for guidance in implementing a REST API that passes and array of key/value pairs

363
Fetch / query data from mongoose using node.js

Fetch / query data from mongoose using node.js

I'm working on a new project, I'm using mongodb and mongoose but the database is already filledIt is filled with imdb movies infos (only the id, title and others informations)

373
Key-only query doesn' work

Key-only query doesn' work

I am trying to query only the key from my entities but I only get a empty object backAll other queries work fine!

301