3

场景1:

我有一个包含 2 个 Typescript 文件的项目,如下所示:

// file:/app/Dogs/Beagle.ts
export module Dogs {
  export Class Beagle {
    public Bark() {
      document.write('Woof');
    }
  }
}

// file:/app/DogPage.ts
import m = module('./Dogs/Beagle');
var b = new m.Dogs.Beagle();
b.Bark();

// file:/config.ts
var require: {baseUrl: '/app'};

这些编译得很好。我还使用 RequireJS 在我的Dogs.html网页上加载文件,使用以下 HTML 代码:

<script src="/app/config.js" type="text/javascript"></script>
<script data-main="DogPage" src="lib/require.js" type="text/javascript"></script>

同样,这很好用,我对 Beagle 对象的使用导致页面上出现“Woof”。

场景2(出现我的问题):

我现在有一个第二个项目,我想在其中使用 Beagle.ts,但我不想只复制 ts 文件,所以我在第三个项目中制作了一个通用副本,我希望从项目 1 和 2 中使用它。

所以我的文件在开发时看起来像这样:

/project1
  /Dogs.html
  /DogPage.ts

/project2
  /MoreDogs.html
  /MoreDogsPage.ts

/project3
  /app
    /Beagle.ts

我计划app在部署时复制 Project3 的文件夹,因此结构如下所示:

/project1
  /Dogs.html
  /DogPage.ts
  /app
    /Beagle.ts

我现在如何将 Beagle.ts 链接到我的 2 个应用程序,以便我可以在开发时实际编译它们,并且仍然让这些路径在生产环境中正常工作?上面的路径将在运行时工作,但我无法在开发时编译代码。

如果我这样做:

import m = module('../../../Dogs/Beagle');

它当然在开发时假定我的硬盘驱动器上的相对位置,并且永远不会在生产中工作。

看来我被困住了,必须在两个项目中维护一份代码副本。对于这个人为的例子来说可能没什么大不了的,但我的真实项目包含许多可重用的类文件。如何组织这个烂摊子并且仍然让它编译?

更新: BASarat 提出的 VS“链接文件”的结果如下:

/*
Compile Error. 
See error list for details
 C:\proj2\app\MoreDogs.ts(2,34) : Incorrect reference: imported file: "./Dogs/Beagle" cannot be resolved.
C:/proj2/app/MoreDogs.ts(2,18): The name ''./Dogs/Beagle'' does not exist in the current scope
C:/proj2/app/MoreDogs.ts(2,18): A module cannot be aliased to a non-module type
C:/proj2/app/MoreDogs.ts(5,12): Expected var, class, interface, or module

*/

如果开发人员使用的是 Visual Studio(这是我不想做的假设),这会产生基于解决方案资源管理器视角的统一代码的错觉,但 TypeScript 不会使用解决方案资源管理器对代码库的理解进行编译,所以编译实际上失败了。我错过了什么吗?

4

2 回答 2

1

You should reconsider your approach. You are developing a library, hence you should treat it as such. Trying to reference the source code of a shared resource is not a solution I would recommend. Furthermore you have already encountered issues trying to solve it this way.

Therefore, my recommendation is to treat your shared project as if it was an external library like i.e. jQuery. You should consider including the output of the shared project as a dependency of the other projects instead of referencing the source directly.

So how would you do this and keep making use of TypeScript? You could provide a definition file for your shared library containing all its definitions to the projects using it. Then require the output of the shared library somewhere in your app entry point to make sure those modules can be referenced. Finally use require("module_name") statements to include those modules where you need them.

The answer to this question used the same method I described above. I didn't flag your question as an exact duplicate however, but the idea is clearly the same.

于 2013-05-27T09:12:57.800 回答
0

将“链接到外部文件”添加到两个项目

http://www.basarat.com/2013/05/add-existing-item-as-link-in-visual.html

于 2013-05-24T02:37:22.183 回答