Unlike Python, TypeScript/JavaScript has a wide variety of module import and export methods.
Currently, ES6 has been standardized, so using import/export is recommended. Due to historical legacy and the huge number of npm libraries, require/exports will continue to coexist for a long time.
1. ES6 Module Import and Export
1.1. Syntax
Three export methods, two import methods
| export | import |
|---|---|
| export var; | import {var} from module |
| export {var}; | import {var} from module |
| export default var | import var from module |
You can also use:
import * as module_alias from module
This imports all exported variables from the module into an object called module_alias.
1.2. Examples
1.2.1. testEs6Export.ts
'use strict'
//Export variable
export const a = '100';
//Export function
export const dogSay = function(){
console.log('wang wang');
}
//Export function - second way
function catSay(){
console.log('miao miao');
}
export { catSay };
//export default export
const m = 100;
export default m;
//export defult const m = 100;// This format cannot be written here.
1.2.2. index.ts
import { dogSay, catSay } from './testEs6Export'; //Imported exported methods
import m from './testEs6Export'; //Imported export default
import * as testModule from './testEs6Export'; //As aggregated object export
2. CommonJS Module Import and Export
2.1. Syntax
The module has a module.exports object, which contains the exported variables.
exports = module.exports = {};
Additionally, there is exports, which is a reference to module.exports.
Use require to retrieve the variables exported by the module.
Note: The actual export is the variable that module.exports points to.
2.2. Example
//utils.js
let a = 100;
console.log(module.exports); //Can print result: {}
console.log(exports); //Can print result: {}
exports.a = 200; //Here, the hard work changes module.exports content to {a : 200}
exports = 'point to other memory area'; //Here, exports is pointed elsewhere
//test.js
var a = require('/utils');
console.log(a) // Prints {a : 200}