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

如何将依赖其他模块的TypeScript转译为浏览器可运行的JavaScript

问题描述

我的工作目录结构如下:

- src
  - functions
  - final
  - utils

我需要将final目录下的两个TypeScript文件转译为可在浏览器中运行的JavaScript,但转译后的JS无法正常加载它们导入的src目录下其他文件的函数和类。

当前的tsconfig.json配置:

{
  "compilerOptions": {
    "target": "es3",
    "lib": ["es6", "dom", "es2017", "ES2021"],
    "module": "commonjs",
    "rootDir": "./src", 
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}
解决方法

问题核心是你使用了commonjs模块格式,而浏览器原生不支持该模块系统,转译后的JS仍保留require这类CommonJS语法,导致浏览器无法识别依赖。以下两种方案可解决问题:

方案一:改用浏览器支持的ES模块格式

  1. 修改tsconfig.json配置,调整模块格式并优化目标版本:
{
  "compilerOptions": {
    "target": "ES6", // 放弃老旧的ES3,改用浏览器普遍兼容的ES6
    "lib": ["es6", "dom", "es2017", "ES2021"],
    "module": "ESNext", // 使用浏览器支持的ES模块格式
    "moduleResolution": "bundler",
    "rootDir": "./src", 
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["src/final/**/*"] // 仅转译final目录下的文件,提升效率
}
  1. 转译完成后,在HTML中通过<script type="module">标签引入生成的JS文件:
<script type="module" src="./dist/final/your-target-file.js"></script>

该方案依赖现代浏览器的ES模块支持,若需兼容老旧浏览器,建议使用打包工具。

方案二:使用打包工具合并依赖(推荐)

浏览器无法自行处理模块依赖链,通过打包工具(如Webpack、Vite)可将所有关联模块合并为浏览器能直接运行的文件。

用Webpack实现:

  1. 安装必要依赖:
npm install webpack webpack-cli ts-loader typescript --save-dev
  1. 新建webpack.config.js配置文件:
const path = require('path');

module.exports = {
  entry: {
    // 配置final目录下的两个文件作为打包入口
    file1: './src/final/file1.ts',
    file2: './src/final/file2.ts'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
  },
};
  1. 修改package.json添加打包命令:
{
  "scripts": {
    "build": "webpack --mode production"
  }
}
  1. 执行npm run build,打包后的文件会输出到dist目录,直接用普通<script>标签引入即可。

用Vite实现(更简洁):

  1. 初始化Vite项目:
npm create vite@latest my-project -- --template vanilla-ts
  1. 将你的src目录内容复制到Vite项目的src文件夹下,在vite.config.js中配置打包入口:
import { defineConfig } from 'vite'

export default defineConfig({
  build: {
    rollupOptions: {
      input: {
        file1: './src/final/file1.ts',
        file2: './src/final/file2.ts'
      }
    }
  }
})
  1. 执行npm run build,生成的dist目录下的文件即可直接在浏览器中运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 06:39:19