【问题标题】:Typescript import text file "error TS2307: Cannot find module"打字稿导入文本文件“错误 TS2307:找不到模块”
【发布时间】:2019-01-22 14:06:59
【问题描述】:

我想将一个文本文件导入我的打字稿文件并简单地打印它。

index.ts 文件:

import d from "./a.txt";
console.log(d);

txt.d.ts 文件:

declare module "*.txt" {
  const value: string;
  export default value;
}

tsconfig.json 文件:

{
  "compilerOptions": {
    "module": "system"
  }
}

package.json 文件:

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "tsc": "tsc",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "typescript": "^3.0.1"
  }
}

但它给了我这个错误

tsc "index.ts"

index.ts:1:15 - 错误 TS2307:找不到模块 './a.txt'。

1 import d from "./a.txt";

npm 错误!代码 ELIFECYCLE npm 错误! errno 2 npm 错误!测试@1.0.0 tsc: tsc "index.ts" npm 错误!退出状态 2 npm ERR! npm 错误!失败于 test@1.0.0 tsc 脚本。 npm 错误!这可能不是问题 与 npm。上面可能还有额外的日志输出。

npm 错误!可以在以下位置找到此运行的完整日志:npm ERR!
C:\Users\SOstad\AppData\Roaming\npm-cache_logs\2018-08-15T16_45_37_115Z-debug.log

文件结构:

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        8/15/2018  11:50 AM                node_modules
-a----        8/15/2018  12:40 PM             12 .gitignore
-a----        8/15/2018  12:22 PM             20 a.txt
-a----        8/15/2018  12:45 PM            112 index.js
-a----        8/15/2018  12:25 PM             43 index.ts
-a----        8/15/2018  11:50 AM            363 package-lock.json
-a----        8/15/2018  11:51 AM            270 package.json
-a----        8/15/2018  12:25 PM             59 tsconfig.json
-a----        8/15/2018  12:25 PM             78 txt.d.ts

【问题讨论】:

    标签: typescript import module


    【解决方案1】:

    由于您只是运行tsc index.ts,因此没有什么会强制加载txt.d.ts。鉴于您有一个tsconfig.json 文件,您可能想要运行tsc -p .。除非您使用捆绑器以您假设的格式捆绑文本文件,否则这在运行时仍然不起作用。

    【讨论】:

    • 那我该怎么办?添加网络包?有什么办法只用打字稿吗?
    • 如果要使用导入,则必须使用捆绑器; Webpack 可能会工作,虽然我自己从未使用过它,也不知道细节。您唯一的其他选择是不使用导入,而是使用目标环境的 API 从正确位置读取文件;在 Node 中这将是 fs.readFile,而在浏览器中它将是 XMLHttpRequest 或 Fetch API。
    • 我将 webpack 添加到我的节点应用程序中,现在它可以工作了。谢谢
    猜你喜欢
    • 2021-03-16
    • 1970-01-01
    • 2016-05-08
    • 2020-03-02
    • 2017-08-02
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多