You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将带调用的require语句转换为ES6的import语法?

Converting require('url-unshort')() to ES6 Modules

Great question! Let's unpack what's going on here and how to convert this CommonJS syntax to proper ES6 modules.

Why the original syntax works

The line const uu = require('url-unshort')() tells us the url-unshort module exports a factory function—not the ready-to-use utility object directly. When you run require('url-unshort'), you retrieve that factory function, and the trailing () immediately calls it to initialize and return the actual uu object you'll use for expanding short URLs.

ES6 Module Conversion Options

Since ES6 modules handle exports differently, here are two reliable ways to replicate this behavior:

Option 1: Default Import + Immediate Invocation

This is the cleanest approach, as we directly import the factory function (which is the module's default export) and call it:

// Import the factory function
import urlUnshortFactory from 'url-unshort';

// Invoke it to get the initialized utility object
const uu = urlUnshortFactory();

// Use it just like before
uu.expand('https://bit.ly/example')
  .then(longUrl => console.log('Expanded URL:', longUrl))
  .catch(err => console.error('Error expanding URL:', err));

Option 2: Using import * as (if you prefer this style)

If you use import * as, you'll get an object containing all exports from the module. The factory function will be under the default property, so you'll need to call that:

// Import all exports into a module object
import * as urlUnshortModule from 'url-unshort';

// Access the default export (the factory function) and invoke it
const uu = urlUnshortModule.default();

// Same usage as above
uu.expand('https://bit.ly/example')
  .then(longUrl => console.log('Expanded URL:', longUrl))
  .catch(err => console.error('Error expanding URL:', err));

Important Note for Node.js

Make sure your project is configured to use ES6 modules:

  • Add "type": "module" to your package.json file.
  • If you're using a file extension, use .mjs instead of .js (though the package.json setting makes .js work for ES6 modules).

内容的提问来源于stack exchange,提问作者Cif

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 16:40:50