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

如何配置TS库使其同时支持ES6、CommonJS及浏览器script标签引入

多环境兼容TS库配置方案

1. 代码逻辑调整

首先在你的库入口文件中,增加全局挂载的条件判断逻辑,只有非模块化环境下才会挂载变量到window,避免污染CommonJS/ES6引入场景的全局空间:

// 原有导出逻辑
export const MyLibName: SDKExport = { /* 你的库代码 */ }

// 新增全局挂载判断
if (typeof exports === 'undefined' && typeof module === 'undefined') {
  // 仅当无模块加载器时执行挂载
  if (typeof window !== 'undefined') {
    (window as any).MyLibName = MyLibName
  }
}

2. 编译配置调整

你当前的tsconfig仅能产出ES6格式产物,需要补充CommonJS和UMD格式产物来适配三种场景,推荐使用Rollup完成多格式打包,操作步骤如下:

2.1 安装依赖

执行以下命令安装打包所需依赖:
npm i rollup @rollup/plugin-typescript @rollup/plugin-terser tslib -D

2.2 新增Rollup配置

在项目根目录新建rollup.config.js文件,内容如下:

import typescript from '@rollup/plugin-typescript';
import terser from '@rollup/plugin-terser';

export default [
  // ES6 模块产物
  {
    input: 'src/index.ts', // 替换为你实际的入口文件路径
    output: {
      file: 'dist/index.esm.js',
      format: 'es'
    },
    plugins: [typescript()]
  },
  // CommonJS 产物
  {
    input: 'src/index.ts',
    output: {
      file: 'dist/index.cjs.js',
      format: 'cjs'
    },
    plugins: [typescript()]
  },
  // 浏览器UMD产物
  {
    input: 'src/index.ts',
    output: {
      file: 'dist/dist.min.js',
      format: 'umd',
      name: 'MyLibName',
      plugins: [terser()]
    },
    plugins: [typescript()]
  }
]

2.3 调整tsconfig.json

新增类型文件生成配置,修改后内容如下:

{
  "compilerOptions": {
    "lib": ["ES2019"],
    "module": "es6",
    "target": "es5",
    "moduleResolution": "node",
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "sourceMap": true,
    "outDir": "build",
    "strict": true,
    "noImplicitAny": true,
    "declaration": true,
    "declarationDir": "dist"
  },
  "include": ["./**/*.ts"],
  "exclude": ["node_modules", ".vscode", "test"]
}

2.4 调整package.json配置

补充产物入口字段和打包脚本:

{
  "main": "dist/index.cjs.js",
  "module": "dist/index.esm.js",
  "browser": "dist/dist.min.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "build": "rollup -c"
  }
}

最终使用效果

执行npm run build后生成的产物会自动适配三种场景:

  • ES6 引入:import { MyLibName } from 'myLib' 正常使用
  • CommonJS 引入:const { MyLibName } = require('myLib') 正常使用
  • 浏览器直接引入:通过CDN引入dist.min.js后,全局自动挂载MyLibName变量,模块化场景下不会触发全局挂载逻辑,不会污染全局空间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:48:03