NodeJS 未定义TypeScript导出,已尝试所有改进技术

s3fp2yjn  于 2023-04-29  发布在  Node.js
关注(0)|答案(1)|浏览(316)

我已经检查了所有StackOverflow关于未定义类型脚本导出的问题的答案,没有一个可以改善这个问题。
我正在关注YouTube教程,视频中的家伙没有问题。
tsconfig.json中,我将target设置为ES6并注解掉了模块。然后我试着将模块设置为commonjs,这也不起作用。编辑:将模块设置为ES6仍然不起作用。
index.html中,我已经将脚本类型设置为模块,并且也尝试了<script>var exports = {"__esModule": true};</script>中的技巧,但没有运气,如果我这样做,我会得到require没有定义。
sandbox.ts:

import { Invoice } from './classes/Invoice';

const form = document.querySelector('.new-item-form') as HTMLFormElement; 

//inputs
const type = document.querySelector('#type') as HTMLSelectElement;
const tofrom = document.querySelector('#tofrom') as HTMLInputElement;
const details  = document.querySelector('#details') as HTMLSelectElement;
const amount  = document.querySelector('#amount') as HTMLSelectElement;

form.addEventListener('submit', (e:Event) => {
    e.preventDefault();
    console.log(
        type.value,
        tofrom.value,
        details.value,
        amount.value
    );
});

//instantiate class
const invOne = new Invoice('test', 'work on test', 250);

console.log (invOne);

let invoice:Invoice[] = []; //only accepts invoice objects in the array
invoice.push(invOne);

interface isPerson{
    name:string;
    age:number;
    speak(a: string):void; //takes a string parameter and returns void
    spend(a:number):number;
}

const me:isPerson = {
    name:"PersonName",
    age:30,
    speak(text:string):void{
        console.log(text);
    },
    spend(amount: number): number {
        console.log('I spent', amount);
        return amount;
    }

    //Adding more properties won't work because they are not inside the interface
}

console.log(me);

Invoice.ts(我试图导入的类):

export class Invoice{
    readonly client:string;
    private details:string;
    public amount:number;

    constructor(c:string,d:string,a:number) {
        this.client = c;
        this.details = d;
        this.amount = a;
    }

    //Method
    format(){
        return `${this.client} owes £${this.amount} for ${this.details}`;
    }
}

index.html:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TypeScript Tutorial</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

<div class="wrapper">
    <h1>Finance Logger</h1>

    <!-- output list -->
    <ul class="item-list">

    </ul>
</div>

<footer>
    <form class="new-item-form">
        <div class="field">
            <label>Type:</label>
            <select id="type">
                <option value="invoice">Invoice</option>
                <option value="payment">Payment</option>
            </select>
        </div>
        <div class="field">
            <label>To / From:</label>
            <input type="text" id="tofrom">
        </div>
        <div class="field">
            <label>Details:</label>
            <input type="text" id="details">
        </div>
        <div class="field">
            <label>Amount (£):</label>
            <input type="number" id="amount">
        </div>
        <button>Add</button>
    </form>

    <a href="https://www.thenetninja.co.uk">The Net Ninja</a>
</footer>

<!-- <script>var exports = {"__esModule": true};</script> -->
<script type="module" src='sandbox.js'></script>
</body>
</html>

编辑:添加沙盒。js内容

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Invoice_1 = require("./classes/Invoice");

var form = document.querySelector('.new-item-form');

var type = document.querySelector('#type');
var tofrom = document.querySelector('#tofrom');
var details = document.querySelector('#details');
var amount = document.querySelector('#amount');
form.addEventListener('submit', function (e) {
    e.preventDefault();
    console.log(type.value, tofrom.value, details.value, amount.value);
});

var invOne = new Invoice_1.Invoice('test', 'work on test', 250);
console.log(invOne);
var invoice = []; //only accepts invoice objects in the array
invoice.push(invOne);
var me = {
    name: "PersonName",
    age: 30,
    speak: function (text) {
        console.log(text);
    },
    spend: function (amount) {
        console.log('I spent', amount);
        return amount;
    }
    //Adding more properties won't work because they are not inside the interface
};
console.log(me);
dbf7pr2w

dbf7pr2w1#

对于像我这样进入TypeScript的新开发者,我不知道你不必每次更新js文件时都运行tsc filename.ts命令。你只需要做tsc。除此之外,这里是一个超级有用的不和谐用户(由Ascor的用户名)给我的配置以及我的问题的答案。
有关tsc命令的文档:https://www.typescriptlang.org/docs/handbook/compiler-options.html
Ascor配置:

{
    "compilerOptions": {
        "target": "esnext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
        "lib": [
            "esnext",
            "dom"
        ], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
        "module": "exnext", /* Specify what module code is generated. */
        "moduleResolution": "nodenext", /* Specify how TypeScript looks up a file from a given module specifier. */
        "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
        "resolveJsonModule": true, /* Enable importing .json files. */
        "outDir": "./dist", /* Specify an output folder for all emitted files. */
        "removeComments": true, /* Disable emitting comments. */
        "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
        "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
        "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
        "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
        "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
        "strict": true, /* Enable all strict type-checking options. */
        "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
    },
    "include": [
        "src/**/*.ts"
    ]
}

相关问题