Live Server 中使用 TypeScript 生成的 JS 文件出现 NS_ERROR_CORRUPTED_CONTENT

问题描述 投票:0回答:1

我现在正在尝试使用普通 TypeScript、HTML 和 CSS 构建一个简单的银行网站,然后添加格子 API 来测试其操作。我目前正在使用 Visual Studio Code 中的 Live Server 在本地测试项目结构。

我的项目结构如下所示:

front-end/
├── dist/
│   ├── main.js
│   ├── login/
│   │   └── login.js
│   ├── dashboard/
│   │   └── dashboard.js
│   └── utils/
│       └── app.js
├── public/
│   ├── index.html
│   ├── login.html
│   └── dashboard.html
├── src/
│   ├── login/
│   │   └── login.ts
│   ├── dashboard/
│   │   └── dashboard.ts
│   └── utils/
│       └── app.ts
└── style/
    └── styles.css

尝试在

app.js
模块中加载
dashboard.js
文件时遇到 NS_ERROR_CORRUPTED_CONTENT 错误。

这是来自控制台的错误消息:

GET http://127.0.0.1:5500/front-end/dist/utils/app NS_ERROR_CORRUPTED_CONTENT

  • MIME 类型错误地设置为 text/html 而不是 application/javascript。
  • 所有路径都是正确的,我可以按住 Ctrl + 单击导航到 VS Code 中的模块。
  • 我已经清除了缓存,重新启动了服务器,并使用 tsc 重建了我的 TypeScript 文件。

.

仪表板代码:

这是

dashboard.js
app.js
中的相关代码:

仪表板.js:

import { fetchBalance, updateBalanceDisplay } from '../utils/app';

export default async function initDashboard() {
    const balance = await fetchBalance();
    updateBalanceDisplay(balance);
}

app.js

export function fetchBalance() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(1250.50);
        }, 1000); // Simulate a network delay
    });
}

export function updateBalanceDisplay(balance: number) {
    const balanceElement = document.getElementById('balance');
    if (balanceElement) {
        balanceElement.textContent = `$${balance.toFixed(2)}`;
    }
}

main.js(路由)

function handleRouting() {
    const path = window.location.pathname;
    if (path.includes('login.html')) {
        import('./login/login').then(module => {
            module.default();
        });
    } else if (path.includes('dashboard.html')) {
        import('./dashboard/dashboard').then(module => {
            module.default();
        }).catch(error => {
            console.error("Error loading dashboard module:", error);
        });
    }
}
handleRouting();

问题:

为什么

app.js
文件以文本/HTML MIME 类型提供,以及如何修复我的设置中的 NS_ERROR_CORRUPTED_CONTENT?

我已经尝试过:

Verified the file paths and ensured they're correct relative to the dist folder.
Cleared browser cache and hard-reloaded the page.
Disabled caching in Live Server settings in VS Code.
Tried loading the app.js file directly in the browser, but it still results in the same error

我希望它至少能显示获取余额功能上的数字!

javascript html typescript mime-types liveserver
1个回答
0
投票

刚刚发现,这是编译器的问题,“.ts”需要在 tsconfig.json 中启用“allowImportingTsExtensions”,如下所示:

{
  "compilerOptions": {
    "allowImportingTsExtensions": true,
    // other options...
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.