简体   繁体   中英

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM