将module.exports从javascript转换为打字稿

时间:2019-06-20 08:26:20

标签: javascript node.js typescript express

我有Node-express代码,其中使用module.exports导出模块。例如,要导出函数,将其编写为module.exports = functionName。现在,代码将转换为打字稿。如何替换打字稿中的module.exports?

4 个答案:

答案 0 :(得分:1)

只需使用export后跟典型的声明,无论它是constfunctioninterfaceenum,您都可以命名。

export const myTestConst = () => console.log('hello world');

请参见https://www.typescriptlang.org/docs/handbook/modules.html

答案 1 :(得分:1)

加到duschsocke答案。您还可以使用公共方法创建一个类,然后在需要这些方法的地方导入该类。

utils.ts

class Utils {

  public static publicFunction() {
    console.log('calling me');
  }
}

在其他ts文件上:

import * as utils from 'utils';

// Call the function
utils.publicFunction(); // Prints 'calling me' on console.

答案 2 :(得分:0)

在模块module.js中,我们可以包含以下代码:

// module "my-module.js"
function cube(x) {
  return x * x * x;
}

const foo = Math.PI + Math.SQRT2;

var graph = {
  options: {
      color:'white',
      thickness:'2px'
  },
  draw: function() {
      console.log('From graph draw function');
  }
}

export { cube, foo, graph };

然后在HTML页面中包含的顶级模块中,我们可以:

import { cube, foo, graph } from 'my-module.js';

graph.options = {
    color:'blue',
    thickness:'3px'
};

graph.draw();
console.log(cube(3)); // 27
console.log(foo);    // 4.555806215962888

使用默认导出

如果我们要为模块导出单个值或具有备用值,则可以使用默认导出:

// module "my-module.js"

export default function cube(x) {
  return x * x * x;
}

然后,在另一个脚本中,很容易导入默认导出:

import cube from './my-module.js';
console.log(cube(3)); // 27

答案 3 :(得分:0)

在TypeScript中,使用export = functionName

相关问题