当需要把大量相同作用范围的函数解耦出去时,新建一个js(位置自定,最好是在负责范围的子目录而不是全部丢一起【虽然丢一起也可以就是,根据需要管理目录结构即可】)。

另外,js文件需要export才能使导入它的文件使用内部函数和值。

例:

// module.js
export const name = 'John';
export function greet() {
    console.log('Hello, ' + name);
}
export class Person {
    constructor(name) {
        this.name = name;
    }
    sayHello() {
        console.log('Hello, my name is ' + this.name);
    }
}

在其他地方引用:

// main.js
import { name, greet, Person } from './module.js';
 
console.log(name); // John
greet(); // Hello, John
const person = new Person('Jane');
person.sayHello(); // Hello, my name is Jane

export default用于导出模块的默认值。一个模块只能有一个默认导出。默认导出可以是变量、函数、类或任何其他值。 例:

// module.js
const name = 'John';
export default name;

在其他模块中导入默认导出时,不需要使用大括号:

// main.js
import name from './module.js';
 
console.log(name); // John

默认导出还可以与命名导出一起使用:

// module.js
export const name = 'John';
export function greet() {
    console.log('Hello, ' + name);
}
 export default class Person {
    constructor(name) {
        this.name = name;
    }
    sayHello() {
        console.log('Hello, my name is ' + this.name);
    }
}

在其他模块中导入时:

// main.js
import Person, { name, greet } from './module.js';
 
console.log(name); // John
greet(); // Hello, John
const person = new Person('Jane');
person.sayHello(); // Hello, my name is Jane

老版本引用方式

CommonJS

// module.js
const a = '1'
function do_something(){
 
};
 
module.exports = {a, do_something}
// main.js
const {a: alias_name} = require('./module')