Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

javascript - Convert prompt-sync require into import method

I use prompt-sync module in my Node project.

 const prompt = require('prompt-sync')();
 const result = prompt(message);

But to keep my TypeScript code consistent I need to use import instead of require. So I installed types for the package.

npm i @types/prompt-sync

And I tried to use it like

import * as promptSync from 'prompt-sync';
...
const prompt = promptSync();
const result = prompt(message);

But the error appeared

Error:(24, 20) TS2349: This expression is not callable.
Type '{ default: (config?: Config | undefined) => Prompt; }' has no call signatures.

So how can I use prompt-sync with import?

question from:https://stackoverflow.com/questions/65852175/convert-prompt-sync-require-into-import-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The error is raised because you cannot call a namespace import (* as ns). This restriction is per the ECMAScript specification which mandates that module namespace objects, such as the aforementioned syntax creates, cannot have a [[Call]] or [[Construct]] signature.

This results in a mismatch when attempting to consume CommonJS modules from ES modules as many of the former export a single function or constructor as the module itself (i.e. module.exports = function () {}).

However, there is interop capability specified and conventionalized which works by synthesizing a default export for the CommonJS module that contains the value of module.exports.

You can and should leverage this interop facility.

Firstly, ensure that "esModuleInterop" is specified with a value of true in your tsconfig.json under "compilerOptions".

Secondly, rewrite your code to import the synthetic default from the prompt-sync module

import promptSync from 'prompt-sync';

const prompt = promptSync();

const result = prompt(message);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...