Search code examples
javascriptimportrequire

How to Convert, in JS, an import statement to a require() statement


I have a Statement in JavaScript:

import app, { set } from '../app';

How can I write an equivalent statement in a form, such as I don't get an error like 'Cannot use import statement outside a module'.

I could convert similar less complex statement by using a format: var Foo = require(foo);

but don't understand how to convert this one.


Solution

  • Not every import can be converted into a require. In pure Node.js this is only possible if the module being required is a CommonJS module, but the situation is different with tools such as Webpack or Babel.

    I image you are using one of those tools, otherwise you would not be able to import ../app without a file extension in the first place: you would need to import from ../app.js or ../app/index.js explicitly, or to use export mappings, but that's a different story.

    Then if

    import app, { set } from '../app';
    

    is a valid import in a ES module, with whatever loader, the equivalent CommonJS syntax would be

    const app = require('../app');
    const { set } = app;