简体   繁体   中英

rewrite require to import statement

I am trying to use https://www.npmjs.com/package/json-bigint with native BigInt support. In CommonJS I'd do:

var JSONbigNative = require('json-bigint')({ useNativeBigInt: true });

What is the ES6 syntax equivalent? This is not working:

import  * as JSONBigIntWrapper from 'json-bigint';
const JSONBigInt = JSONBigIntWrapper({useNativeBigInt: true});

as it complains that JSONBigIntWrapper is not a function.

What are the generic rules for rewriting rewrite to import?

With ES6 imports, importing * is not the equivalent of what require() does.

What you are looking to get is the default module export, as shown in the code below

import whatever_you_want_the_default_to_be_named, {} from 'json-bigint'

You can rely on using the default keyword when importing the default export from a module.

import {default as _JBI} from 'json-bigint';
const JSONBigNative = _JBI({useNativeBigInt: true});

This is also the only syntax which works when using dynamic import syntax :

const {default: _JBI} = await import('json-bigint');
const JSONBigNative = _JBI({useNativeBigInt: true});

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