js-library-distribution
Patterns for developing distributable JavaScript/TypeScript libraries. Use when building npm packages, SDK libraries, or any code that runs in customer environments.
安装与使用
请根据来源仓库和你的 AI 工具说明安装此技能。先阅读技能文件和依赖要求,再添加到工作流。
查看来源 ↗使用指南技能说明
Library Distribution Patterns
Critical: No Global Pollution
Distributable libraries run in customer environments alongside unknown code. Global pollution can break customer sites.
NEVER Modify Global Objects
// ❌ CRITICAL: Never extend native prototypes
Array.prototype.customMethod = function() { ... }
String.prototype.format = function() { ... }
Object.prototype.toJSON = function() { ... }
// ❌ CRITICAL: Never modify third-party libraries
import _ from 'lodash'
_.customUtil = function() { ... } // Pollutes lodash globally
// ❌ CRITICAL: Never assign to window/global
window.MyLib = { ... }
globalThis.MyLib = { ... }
Safe Patterns
// ✅ Export your own functions
export function customMethod(arr: unknown[]) { ... }
export function format(str: string) { ... }
// ✅ Use composition, not extension
import { map } from 'lodash'
export function customMap<T>(arr: T[]) {
return map(arr, /* your logic */)
}
// ✅ If global is unavoidable, use unique namespace
const UNIQUE_NAMESPACE = '__myCompany_myLib_v1__'
if (typeof window !== 'undefined') {
(window as any)[UNIQUE_NAMESPACE] = { ... }
}
No Side Effects on Import
// ❌ BAD: Side effects when imported
// This runs immediately when someone imports your library
console.log('Library loaded')
fetch('/api/init')
document.addEventListener('DOMContentLoaded', ...)
// ✅ GOOD: Explicit initialization
export function init(config: Config) {
// Side effects only when user explicitly calls
}
Bundle Considerations
Tree-Shaking Support
// ✅ Use named exports for tree-shaking
export { functionA } from './a'
export { functionB } from './b'
// ❌ Barrel exports can break tree-shaking
export * from './everything'
Dual Package (ESM + CJS)
{
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs",
"types": "./dist/index.d.ts"
}
}
}
Dependency Management
// ❌ BAD: Bundling dependencies (version conflicts)
// Your lodash 4.x vs customer's lodash 3.x
// ✅ GOOD: Peer dependencies
// package.json
{
"peerDependencies": {
"lodash": "^4.0.0"
}
}
Checklist Before Publish
- No
prototypemodifications - No third-party library modifications
- No implicit globals (
window.X,globalThis.X) - No side effects on import
- Named exports for tree-shaking
- Peer dependencies declared
- Tested in isolation AND alongside common libraries
使用示例
查看来源仓库中的使用示例与配置说明。
查看来源 ↗来源历史
- 收录时间
- 2026-03-11
- 索引更新时间
- 2026-03-11
- Branch
- main
收录与同步日期属于本站记录。源码修改历史请查看来源仓库。
GitHub ↗chat Comments (0)
Sign in to join the discussion and leave a comment.
No comments yet. Be the first to share your thoughts!