按 NodeJS 中的依赖项对 TypeScript 文件进行排序
Sort TypeScript files by dependencies in NodeJS
我有一些文件,其中一些具有依赖性,而另一些则没有。
还有 cicle 依赖项。我想按此依赖项对这些文件进行排序,以便稍后以正确的顺序连接这些文件。
这是 TypeScript 文件,但我在 NodeJS 程序中收集了所有文件,我想在其中对 TypeScript 文件进行排序。
示例(这只是随机名称):
这里有两个选项,第一个基本上是"you don't need to",另一个是用工具把Humpty Dumpty拼在一起
- 如果您在编译 TypeScript 时使用 commonjs 作为模块参数,Node 将为您处理
require
,然后 运行Node 将在运行时为您加载依赖项
- 您可以使用 webpack/browserify 等工具来 concat/bundle 您的输出,这些工具将分析您的依赖关系并将 files/contents 以正确的顺序放入单个输出文件中
您可以将参考标签放在每个文件的顶部,并使用 --out
CLI 选项。 TSC 将找出其余部分。循环依赖不会破坏 TSC,但您确实需要考虑到某些东西在运行时可能还不存在。
Shape.ts
/// <reference path="Test.ts"/>
Test.ts
/// <reference path="Vector.ts"/>
Vector.ts
/// <reference path="Group.ts"/>
/// <reference path="Shape.ts"/>
感谢一些我已经知道的事情的回答,我自己找到了正确的答案,这是我的解决方案:
var stack = [];
var visited = [];
function topologicalSortUtil(item) {
visited.push(item.fullPath);
for (var i = 0; i <= item.dependencies.length - 1; i++) {
var dependency = item.dependencies[i];
if (visited.indexOf(dependency.fullPath) !== -1) {
continue;
}
topologicalSortUtil(dependency);
}
stack.push(item);
}
function topologicalSort(data) {
for (var i = 0; i <= data.length - 1; i++) {
var item = data[i];
if (visited.indexOf(item.fullPath) !== -1) {
continue;
}
topologicalSortUtil(item);
}
return stack;
}
参考文献:
https://en.wikipedia.org/wiki/Topological_sorting
https://www.youtube.com/watch?v=ddTC4Zovtbc
https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/TopologicalSort.java
我有一些文件,其中一些具有依赖性,而另一些则没有。 还有 cicle 依赖项。我想按此依赖项对这些文件进行排序,以便稍后以正确的顺序连接这些文件。
这是 TypeScript 文件,但我在 NodeJS 程序中收集了所有文件,我想在其中对 TypeScript 文件进行排序。
示例(这只是随机名称):
这里有两个选项,第一个基本上是"you don't need to",另一个是用工具把Humpty Dumpty拼在一起
- 如果您在编译 TypeScript 时使用 commonjs 作为模块参数,Node 将为您处理
require
,然后 运行Node 将在运行时为您加载依赖项 - 您可以使用 webpack/browserify 等工具来 concat/bundle 您的输出,这些工具将分析您的依赖关系并将 files/contents 以正确的顺序放入单个输出文件中
您可以将参考标签放在每个文件的顶部,并使用 --out
CLI 选项。 TSC 将找出其余部分。循环依赖不会破坏 TSC,但您确实需要考虑到某些东西在运行时可能还不存在。
Shape.ts
/// <reference path="Test.ts"/>
Test.ts
/// <reference path="Vector.ts"/>
Vector.ts
/// <reference path="Group.ts"/>
/// <reference path="Shape.ts"/>
感谢一些我已经知道的事情的回答,我自己找到了正确的答案,这是我的解决方案:
var stack = [];
var visited = [];
function topologicalSortUtil(item) {
visited.push(item.fullPath);
for (var i = 0; i <= item.dependencies.length - 1; i++) {
var dependency = item.dependencies[i];
if (visited.indexOf(dependency.fullPath) !== -1) {
continue;
}
topologicalSortUtil(dependency);
}
stack.push(item);
}
function topologicalSort(data) {
for (var i = 0; i <= data.length - 1; i++) {
var item = data[i];
if (visited.indexOf(item.fullPath) !== -1) {
continue;
}
topologicalSortUtil(item);
}
return stack;
}
参考文献:
https://en.wikipedia.org/wiki/Topological_sorting
https://www.youtube.com/watch?v=ddTC4Zovtbc
https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/TopologicalSort.java