
По сути, я пытаюсь создать простой html-файл с отдельным файлом TS (greeter.ts), который импортирует класс из MyClass.ts. Проблема в том, что браузер не видит модуль, скомпилированный в Javascript. Я не уверен, какие настройки необходимы в tsconfig, поскольку я перепробовал практически все параметры внутри "module", "target" и "moduleResolution".
В файле Greetinger.ts я пытаюсь импортировать класс MyClass из MyClass.ts
и использовать его для записи в div в index.html
const appDiv_1 = document.getElementById("app_1");
Ниже кода MyClass приведен простой фрагмент, который записывает в другой элемент div в index.html.
Это src/greeter.ts
Код: Выделить всё
import {MyClass} from './MyClass';
const myInstance = new MyClass("TypeScript in HTML");
const appDiv_1 = document.getElementById("app_1");
if (appDiv_1)
appDiv_1.innerText = myInstance.greet();
const appDiv_2 = document.getElementById("app_2");
if (appDiv_2)
appDiv_2.innerText = "works";
Код: Выделить всё
export class MyClass
{
private message: string;
constructor(msg: string)
{
this.message = msg;
}
greet(): string {
return `Hello from MyClass: ${this.message}`;
}
}
Код: Выделить всё
{
"compilerOptions": {
"module": "NodeNext", // or "ES2020", "ES6", etc.
"target": "esNext",
"moduleResolution": "nodenext",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"paths": {
"undici-types": ["./node_modules/undici-types/index.d.ts"]
}
},
"include": ["src/**/*.ts" ]
}
Код: Выделить всё
{
"name": "typescript-browser-example",
"version": "1.0.0",
"description": "A simple TypeScript example for the browser",
"main": "dist/greeter.js",
"scripts": {
"build": "tsc"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"typescript": "^5.0.0"
}
}
Код: Выделить всё
TypeScript Example
Код: Выделить всё
main_folder
|__src
| greeter.ts
| MyClass.ts
|__dist
greeter.js
MyClass.js
|tsconfig.json
|package.json
|node_modules
tsc
в bash на Ubuntu Linux.
Подробнее здесь: https://stackoverflow.com/questions/798 ... html-not-s
Мобильная версия