You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS Code配置含npm模块的前端TypeScript项目解决方案咨询

前端TypeScript项目浏览器无法加载npm模块的解决方案

问题背景

我有一个使用TypeScript开发的Web项目,在VS Code中可以正常导入、查看并使用npm模块,但浏览器加载页面时,npm模块无法被找到。手动从npm模块中提取library.js复制到项目根目录后,浏览器能正常使用该库,但这种方式会丢失npm的版本管理、依赖更新等核心优势。

我希望通过定义输出目录,将TypeScript编译后的文件、HTML页面及依赖的npm模块统一复制到该目录,以此解决浏览器加载问题。另外,我有一个TypeScript编写的Node.js Express项目,导入的库可以直接正常工作,希望前端TypeScript项目也能实现类似的便捷性。

目前我未使用webpack等打包工具,正在学习相关内容;也了解到import maps,但不确定本地开发时如何使用。我的核心需求是在项目中使用base-class-ts模块的BaseClass.ts。

项目结构

/mypage.html
/myproject.ts(我的TypeScript文件)
/myproject.js(TypeScript编译生成的JavaScript文件)
/tsconfig.json
/.vscode/tasks.json

当前配置与错误信息

.vscode/tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "typescript",
            "tsconfig": "tsconfig.json",
            "option": "watch",
            "problemMatcher": [
                "$tsc-watch"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "label": "tsc: watch - tsconfig.json"
        }
    ]
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs", 
    "inlineSourceMap": true,
    "esModuleInterop": true,  
    "forceConsistentCasingInFileNames": true, 
    "strict": true,
    "noImplicitOverride": true,
    "allowUnreachableCode": true,
    "skipLibCheck": true
  }
}

浏览器报错

script.js:2 Uncaught ReferenceError: exports is not defined
    at script.js:2:23

简化版HTML代码

<script type="module">
import {BaseClass} from "base-class-ts"

export class MyClass extends BaseClass {

    constructor() {
        super();
        console.log("Hello world")
    }
}

BaseClass.startWhenReady(MyClass);
</script>

具体疑问

  • 能否通过tsconfig.json或jsconfig.json实现输出目录的文件整合?是否存在webconfig.json或VS Code相关配置,可以将目录中所有文件(包括引用的npm模块)复制到另一个指定目录?
  • 不使用打包工具的情况下,如何在本地开发中使用import maps解决npm模块的浏览器导入问题?
  • 如果使用打包工具(如webpack)解决,如何配置以支持source maps?

内容的提问来源于stack exchange,提问作者1.21 gigawatts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 09:42:46