在浏览器中解析打字稿模块会产生404 [英] Resolving typescript modules in the browser yields a 404

查看:34
本文介绍了在浏览器中解析打字稿模块会产生404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个使用 typescript 创建的Web应用程序的小示例.我在导入模块时遇到问题.

I am looking to put together a small example of for a web app that is created using typescript. I have an issue with importing a module.

我只想知道为什么这是错误的,以及我必须对其进行排序的选项.

I just want information on why this is wrong and what options I have to sort it.

问题是尝试导入hello时index.js文件中的404.

The problem is a 404 for the in the index.js file when trying to import the hello.

这是代码:

<!DOCTYPE html>
<html>
    <head>
        <title>Hello World</title>
    </head>
    <body>
        <p>Check the console log...</p>
    </body>

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

index.ts

import { HelloWorld } from "./hello";

var helloWorld = new HelloWorld();

helloWorld.sayHello();

hello.ts

export class HelloWorld {
    constructor() {

    }

    sayHello() {
        console.log("Hello, world!");
    }
}

tsconfig.json

{
    "compilerOptions": {
      "target": "ES2015",
      "module": "ES2015",
      "lib": ["es2015", "dom"],
      "moduleResolution": "node",

      "allowJs": true,
      "checkJs": true,
      "sourceMap": true,
      "outDir": "./dist",
      "strict": true,
      "esModuleInterop": true,
      "experimentalDecorators": true,
      "forceConsistentCasingInFileNames": true
    }
  }

以上使用 tsc 编译应用程序的输出如下:

The output of the above using tsc to compile the app is as follows:

dist
    hello.js
    hello.js.map
    index.js
    index.js.map

这些如下:

export class HelloWorld {
    constructor() {
    }
    sayHello() {
        console.log("Hello, world!");
    }
}
//# sourceMappingURL=hello.js.map

index.js

import { HelloWorld } from "./hello";
var helloWorld = new HelloWorld();
helloWorld.sayHello();
//# sourceMappingURL=index.js.map

现在,如果我将 index.ts 更改为完整的 hello.js 而不是 hello ,那么它将起作用.感觉不对-因为在编写代码时没有 index.js .

Now if I change the index.ts to the full hello.js instead of hello then this will work. This feels wrong - as there is no index.js whilst I am coding this.

解决此问题的正确方法是在兼容Chrome的 ES2015 浏览器中运行?

What is the correct way of resolving this to run in an ES2015 compatible browser such as Chrome?

我是否必须使用诸如 requirejs 之类的东西?

Do I have to use something such as requirejs?

推荐答案

您可以在打字稿中使用从'./hello.js'导入h.
另请阅读此线程 https://github.com/microsoft/TypeScript/issues/16577

You can use import h from './hello.js' in your typescript.
Also read this thread https://github.com/microsoft/TypeScript/issues/16577

这篇关于在浏览器中解析打字稿模块会产生404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆