如何将依赖其他模块的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模块格式
- 修改
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目录下的文件,提升效率 }
- 转译完成后,在HTML中通过
<script type="module">标签引入生成的JS文件:
<script type="module" src="./dist/final/your-target-file.js"></script>
该方案依赖现代浏览器的ES模块支持,若需兼容老旧浏览器,建议使用打包工具。
方案二:使用打包工具合并依赖(推荐)
浏览器无法自行处理模块依赖链,通过打包工具(如Webpack、Vite)可将所有关联模块合并为浏览器能直接运行的文件。
用Webpack实现:
- 安装必要依赖:
npm install webpack webpack-cli ts-loader typescript --save-dev
- 新建
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'), }, };
- 修改
package.json添加打包命令:
{ "scripts": { "build": "webpack --mode production" } }
- 执行
npm run build,打包后的文件会输出到dist目录,直接用普通<script>标签引入即可。
用Vite实现(更简洁):
- 初始化Vite项目:
npm create vite@latest my-project -- --template vanilla-ts
- 将你的
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' } } } })
- 执行
npm run build,生成的dist目录下的文件即可直接在浏览器中运行。
内容的提问来源于stack exchange,提问作者JoaoPedroMatias
相关产品推荐
相关产品推荐

