0
点赞
收藏
分享

微信扫一扫

JavaScript核心功能之模块命名冲突的解决方式

避免模块命名冲突的三种解决方式

方式一:使用as重命名导出与导入

在你的 import 和 export 语句的大括号中,可以使用 as 关键字跟一个新的名字,来改变你在顶级模块中将要使用的功能的标识名字。


第一种方法:在export中使用as

// inside module.js
export {
function1 as newFunctionName,
function2 as anotherNewFunctionName
};

// inside main.js
import { newFunctionName, anotherNewFunctionName } from '/modules/module.js';


第二种方法:在import中使用as

// inside module.js
export { function1, function2 };

// inside main.js
import { function1 as newFunctionName,
function2 as anotherNewFunctionName } from '/modules/module.js';

方式二:创建模块对象

上面的方法工作的挺好,但是有一点点混乱、亢长。一个更好的解决方是,导入每一个模块功能到一个模块功能对象上


import * as Module from '/modules/module.js';

 

方式三、模块与类(class)

导出和导入类,是避免代码冲突的另一种选择

导出

class Square {
constructor(ctx, listId, length, x, y, color) {
...
}

draw() {
...
}

...
}


export { Square };

 

导入

import { Square } from './modules/square.js';

let square1 = new Square(myCanvas.ctx, myCanvas.listId, 50, 50, 100, 'blue');
square1.draw();
square1.reportArea();
square1.reportPerimeter();

 






你投入得越多,就能得到越多得价值



举报

相关推荐

0 条评论