【问题标题】:typescript import create error after transpilation转译后打字稿导入创建错误
【发布时间】:2022-08-18 07:02:15
【问题描述】:

为了练习,我创建了一个简单的 TS 项目,


如果有帮助,我的 ts.config

{
  \"compilerOptions\": {
    \"target\": \"es2016\",
    \"module\": \"commonjs\",
    \"outDir\": \"./dist\",
    \"esModuleInterop\": true,
    \"forceConsistentCasingInFileNames\": true,
    \"strict\": true,
    \"skipLibCheck\": true
  }
}

我的“项目树”非常简单:

在 html 中,我已经在 -head- 中导入了脚本:

    <script defer type=\"module\" src=\"./dist/index.js\"></script>

“classreminder.ts”:

export class ClassTestReminder {
  attribut: string;

  constructor(attribut: string) {
    this.attribut = attribut;
  }

  sayhello() {
    console.log(`hello ${this.attribut}`);
  }
}

在 index.ts 中导入:

    import {ClassTestReminder} from \"./class/classreminder\";

     // other code...
     // form / input / button management
    
    const newObjectTest: ClassTestReminder = new ClassTestReminder(\"name\");
    
    newObjectTest.sayhello();

问题是,我以以下错误结束:

Uncaught ReferenceError: exports is not defined
    <anonymous> http://127.0.0.1:5500/dist/index.js:2
index.js:2:1

并且 index.js 确实有这一行 1 & 2 :

\"use strict\";
Object.defineProperty(exports, \"__esModule\", { value: true });

我从这里尝试了多种解决方案: Uncaught ReferenceError: exports is not defined in filed generated by Typescript

可悲的是,没有什么对我有用(除非我忘记了一些未指定的细节)


我在某处读过评论来自 ts.config 的 \"module\": \"commonjs\"。 试过了,js 现在在第 1 行有一个“经典导入”

import {ClassTestReminder} from \"./class/classreminder\";

但是浏览器给我带来了另一个错误,例如:\”由于不允许的 mime 类型 ( text/html ),模块被阻止\"

尝试对我导入脚本的方式进行不同的更改,但仍然没有任何效果(ofc 如果我评论导入,那么类实例一切正常,如果我在 index.ts 中创建类,则相同)

任何人都知道我缺少什么让导入正常工作?

谢谢 !

    标签: javascript typescript import


    【解决方案1】:

    解决了我的问题,嗯,有点。

    如果我评论

    //"module": "commonjs",
    

    到目前为止,我理解使 ts 在 ES6 中转译,而不是在 ES5 中(这就是为什么 js 中的导入与您通常声明它们的方式相同的原因)

    并在 TS 文件中的每个导入末尾添加一个 .js (在 TS 文件中是),以具有以下内容:

     import {ClassTestReminder} from "./class/classreminder.js";
    

    这样,TS /导入就没有问题,因此项目和浏览器中的“liveserver”也没有问题 但是..由于注释了“模块”:“commonjs”,我无法再在终端中运行该项目了...

    如果有人有更好的选择,我会很感兴趣。

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-29
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 2017-06-26
      • 1970-01-01
      • 2022-11-14
      相关资源
      最近更新 更多