导出变量和函数calc.js
export const name = 'calc';
export const add = (x, y) => {
return x + y;
};
export const subtract = (x, y) => {
return x - y;
};
导入变量和函数,并加以使用
import * as calc from './calc';
const x = 3;
const y = 5;
console.log(`${calc.name}`);
const result_add = calc.add(x, y);
console.log(`${x} + ${y} = ${result_add}`);
const result_subtract = calc.subtract(x, y);
console.log(`${x} - ${y} = ${result_subtract}`);
另一种导入方法
import {name, add, subtract} from './calc';
const x = 3;
const y = 5;
console.log(`${name}`);
const result_add = add(x, y);
console.log(`${x} + ${y} = ${result_add}`);
const result_subtract = subtract(x, y);
console.log(`${x} - ${y} = ${result_subtract}`);
默认导出(多个函数或变量只能导出一个默认的)calc.js
export const name = 'calc';
const add = (x, y) => {
return x + y;
};
export const subtract = (x, y) => {
return x - y;
};
export { add as default };
导入并使用
import adds,{name,subtract} from './calc';
const x = 3;
const y = 5;
console.log(`${name}`);
const result_add = adds(x, y);
console.log(`${x} + ${y} = ${result_add}`);
const result_subtract = subtract(x, y);
console.log(`${x} - ${y} = ${result_subtract}`);
默认导出一个对象
export default {
name: 'calc',
add: (x, y) => {
return x + y;
},
subtract: (x, y) => {
return x - y;
}
};
导入并使用
import calc from './calc';
const x = 3;
const y = 5;
console.log(`${calc.name}`);
const result_add = calc.add(x, y);
console.log(`${x} + ${y} = ${result_add}`);
const result_subtract = calc.subtract(x, y);
console.log(`${x} - ${y} = ${result_subtract}`);
导出一个类
export default class Calc {
constructor (x, y) {
this.x = x;
this.y = y;
}
add () {
return this.x + this.y;
}
subtract () {
return this.x - this.y;
}
}
导入并使用
import Calc from './calc';
const x = 3;
const y = 5;
const calc = new Calc(x, y);
const result_add = calc.add();
console.log(`${x} + ${y} = ${result_add}`);
const result_subtract = calc.subtract();
console.log(`${x} - ${y} = ${result_subtract}`);