【问题标题】:Import a ts file to another ts file using es6 syntax without transpiler使用 es6 语法将一个 ts 文件导入另一个 ts 文件,无需转译器
【发布时间】:2017-04-06 08:23:44
【问题描述】:

假设我在文件夹 folder1 下有一个 ts 文件 文件夹 1->apptest.ts 在这个文件中,我正在写 import * as chai from "chai" 如果 chai.js 不在同一个文件夹中意味着 folder1 它抛出错误模块找不到 如果我将 chai.js 复制到 folder1 则错误消失 我们可以在不使用任何转译器的情况下导入另一个文件夹中的文件吗

【问题讨论】:

  • 你安装chai了吗?尝试使用npm install chai 安装,打字稿将找出node_modules 文件夹中的模块。
  • 我没有遵循 node_modules 结构,我正在将 chai 与 msbuild 集成。但这里的要点与 chai 无关,我说的是任何 ts 文件或 js 文件假设 sample.js 在 apptest 中使用.ts
  • 让我描述一下我在文件资源管理器中的文件夹结构 **-- src->client.sln->something.csproj->app.ts 我的测试项目就像 **-- src- client.sln->test.csproj->apptest.ts 我的 app.ts 有一个方法 Showname(name:string) 我想使用它所以在这种情况下我在 apptest.ts 中导入 app.ts 就像 import * as名称来自“应用程序”,但在这种情况下,我收到错误找不到模块应用程序,我已将应用程序导出为模块。如果我将 app.ts 的 app.js 文件复制到 apptest.ts 文件夹,则错误得到解决。
  • 不,你不能在没有转译器的情况下使用打字稿。

标签: typescript ecmascript-6


【解决方案1】:

您可以在 apptest.ts 中使用精确路径:

import Showname from '/src/client.sln/something.csproj/app'; 

但是你必须记住 typescript 会被编译成 JS。所以编译后的文件“app.js”必须和ts文件在同一个文件夹(/src/client.sln/something.csproj/)。如果你使用 outDir 编译选项,你可以使用像import x from '../../something.csproj' 这样的相对路径。

但更正确的做法是:将 app.ts 用作模块(参见 npm linknpm publish 文档)

【讨论】:

  • 有没有办法通过打字来实现??
  • 不,因为在生成 JS 时,不会有任何类型(在运行时)。
  • 我的错误是在编译时,所以我认为 tsc 默认在 Typings 文件夹中搜索声明文件。
猜你喜欢
  • 2018-08-09
  • 2019-12-04
  • 2019-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多