Typescript编译成模块.导出匿名函数

6tqwzwtp  于 2023-03-31  发布在  TypeScript
关注(0)|答案(1)|浏览(135)

我目前在index.ts中有以下代码

export default (name: string): string => {
  return 'Hi ' + name;
}

编译后的index.js必须作为结果

module.exports = (name) => {
  return 'Hi ' + name:
}

然而,无论我尝试什么,它总是返回我与

exports.default = (function(name) => {
  return 'Hi' + name;
})
  • 包.json*
{
  "compilerOptions": {
    "module": "commonjs",
    "outDir": "dist/cjs",
    "target": "ES5",
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "baseUrl": "src",
    "declaration": true,
    "esModuleInterop": true,
    "inlineSourceMap": false,
    "lib": ["esnext"],
    "listEmittedFiles": false,
    "listFiles": false,
    "moduleResolution": "node",
    "noFallthroughCasesInSwitch": true,
    "pretty": true,
    "resolveJsonModule": true,
    "rootDir": "src",
    "skipLibCheck": true,
    "strict": true,
    "traceResolution": false,
    "types": ["node"],
    "ignoreDeprecations": "5.0"
}
crcmnpdw

crcmnpdw1#

不能简单地用require("package")()调用export default函数,因为export default在js中被翻译为

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = (name) => {
    return "Hi " + name;
};

所以你应该用require("package").default("name")调用这个箭头函数。
请记住,exportsmodule.exports的别名
然而,有一个“技巧”可以在没有.default的情况下调用它,重新绑定export

export = (name: string): string => {
  return "Hi " + name;
};

这被翻译成

"use strict";
module.exports = (name) => {
    return "Hi " + name;
};

让我们试试看:

$ node -e "console.log(require('./index')('rodolfo'))"
Hi rodolfo

相关问题