I have Node-express code where modules are exported by using module.exports. For example, to export a function, it is written module.exports = functionName. Now the code will be converted to typescript. How to replace module.exports in typescript?
Just use export
followed by the typical declaration, no matter whether it is a const
, function
, interface
, enum
, you name it.
export const myTestConst = () => console.log('hello world');
See https://www.typescriptlang.org/docs/handbook/modules.html
Adding up to duschsocke answer. You can also create a class with public methods and importing that class where you need those methods.
utils.ts
class Utils {
public static publicFunction() {
console.log('calling me');
}
}
On other ts file:
import * as utils from 'utils';
// Call the function
utils.publicFunction(); // Prints 'calling me' on console.
In a module module.js, we could include the following code:
// 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 };
Then in the top-level module included in your HTML page, we could have:
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
Using the default export
If we want to export a single value or to have a fallback value for your module, you could use a default export:
// module "my-module.js"
export default function cube(x) {
return x * x * x;
}
Then, in another script, it is straightforward to import the default export:
import cube from './my-module.js';
console.log(cube(3)); // 27
在TypeScript中,使用export = functionName
。
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.