skip to Main Content

My project is written entirely in CommonJS module and I can’t change it. I am trying to use a library which is an ESM. The library is Got library (https://github.com/sindresorhus/got).

This is my code

const request = require('request');
const Promise = require('bluebird');
// require('./wrapped-got');
var wrappedgot = null;

function HTTPRequestV2(hostURL, defaultOptions) {
    this.hostUrl = hostURL;
    this.requestWrapper = request.defaults(defaultOptions);
}


HTTPRequestV2.prototype.init = async function(){
    wrappedgot = await import('got');
    /*return import('got')
        .then(({default: theDefault}) => {
            wrappedgot= theDefault;
            console.log(theDefault);

        });
    console.log(wrappedgot);*/
};

But on running this I get error Not Supported on the wrappedgot = await import(‘got’); line

I tried using the work around of dynamic import function as suggested in their Issues page but its failing with above error
https://github.com/sindresorhus/got/issues/1789

Even tried running their sample code but that is also failing with same error
https://gist.github.com/szmarczak/0f2b70b2a1ed52a56a6d391ac02d094d

——Update——-

I am using Node Version 12.14.1, it supports async & await.
I have read in SO where it has been used in Node Version 10

Using the dynamic import() function on Node.js

Got Library version is 13.0.0

2

Answers


  1. I’m pretty sure imports have to be in the global scope and you’re trying to use an import inside of a function. You will have to move that import outside of that function in order for the error to go away. As a solution to this, import ‘got’ at the top with those requires and assign it to a variable and then when the function HTTPRequestV2.prototype.init is run then you should set ‘wrappedgot’ to whatever variable holds the ‘got’ import. I hope this helps.

    <—————— General improvements to this code ——————>

    Also this is unrelated but you’ve named a variable at the top ‘Promise’ and that should really be avoided since a promise is a constructor function in JavaScript and is used for something else, by using it’s name for something else it could result in actual promises to throw an error.

    I would also suggest not using ‘var’ in this day and age since it’s a legacy version of JavaScript and can result in unexpected bugs that you might not expect unless you know what you are doing.

    I would also recommend on using import instead of require to stay up to date with the latest implementations.

    Login or Signup to reply.
  2. Node.js 12.x does not support dynamic imports. Additionally, it has been over a year since security support for Node.js 12.x ended.

    Upgrade to a current version of Node.Js.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search