configure-bundler-build
Skill9 starsChanged 5 months agoApache-2.0View on GitHub
Configures and optimizes the JS/TS build toolchain — tsconfig plus a bundler (Vite/esbuild/Rollup/tsup/webpack) — for correct module output (ESM/CJS/dual + types), code splitting, tree-shaking, sourcemaps, env injection, and fast incremental builds.
- Reads credentials
- Deletes or force-pushes
In this repository147 other files it gives its agents.
- second-brain/AGENTS.mdAGENTS.md
- second-brain/CLAUDE.mdCLAUDE.md
- agent-tool-mcp-builderSkill
- api-design-reviewSkill
- async-concurrency-correctnessSkill
- audit-accessibility-wcagSkill
- audit-license-complianceSkill
- audit-technical-seoSkill
- auth-jwt-sessionSkill
- author-codemodSkill
- brainstorm-designSkill
- build-audit-loggingSkill
- build-cdc-streaming-pipelineSkill
- build-cli-toolSkill
- build-data-tableSkill
- build-etl-pipelineSkill
- build-form-validationSkill
- build-native-mobile-uiSkill
- build-office-docsSkill
- build-offline-first-syncSkill
- build-react-componentSkill
- build-realtime-channelSkill
- build-spreadsheetSkill
- build-vector-searchSkill
- caching-strategySkill
- cicd-pipeline-authorSkill
- cloud-cost-optimizeSkill
- code-commentsSkill
- code-reviewSkill
- compose-local-dev-stackSkill
- configure-dns-tlsSkill
- configure-reverse-proxy-lbSkill
- configure-security-headers-cspSkill
- contract-testingSkill
- datetime-timezone-correctnessSkill
- db-migration-safetySkill
- debug-ci-pipeline-failureSkill
- debug-flaky-testsSkill
- debug-frontend-browserSkill
- debug-root-causeSkill
- defend-llm-prompt-injectionSkill
- deliver-webhooksSkill
- dependency-upgradeSkill
- deploy-releaseSkill
- design-api-paginationSkill
- design-authorization-modelSkill
- design-backup-dr-recoverySkill
- design-event-sourcing-cqrsSkill
- design-multi-tenancySkill
- design-protobuf-grpc-serviceSkill
- design-relational-schemaSkill
- design-search-index-infraSkill
- design-state-machineSkill
- design-token-systemSkill
- diff-table-paritySkill
- distributed-locks-leasesSkill
- dockerfile-optimizeSkill
- encrypt-sensitive-dataSkill
- error-messageSkill
- estimate-workSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
4 rules. About 0 are common, 1 is distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 38
Default: app → Vite, library → tsup, node-tool → esbuild.
- Very specific: line 103
Keep peerDependencies (react, etc.) in external so you don't bundle two copies into the consumer.
- Distinctive: line 118
Don't over-split (HTTP/2 helps, but hundreds of tiny chunks add request + parse overhead).
- Very specific: line 131
Anything bundled for the browser is public: Put API keys/DB URLs behind a server route or read them at runtime on the server (process.env) …
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
When to Use
Reach for this skill when the problem is how source compiles and emits, not how it runs in a browser or container:
- "Set up the build for this app/library" (pick bundler, tsconfig, output format)
- "My library ships ESM but breaks in a CJS
require()" (or vice versa) — dual-package output - "Consumers get
Could not find a declaration file" — missing/mislocated.d.ts - "Tree-shaking isn't dropping unused exports" — dead code in the bundle
- "
tsc/vite buildis slow" — switch transform to esbuild/swc, add a persistent cache - "
define/import.meta.envisn't replacing my env var" or a secret leaked into the client bundle - tsconfig errors:
module/moduleResolutionmismatch,"x.js" has no exported member, paths not resolving
NOT this skill:
- Shrinking the runtime container image, multi-stage Docker layers → dockerfile-optimize
- LCP/INP/CLS, lazy-loading images, render-blocking JS in the browser → optimize-core-web-vitals
- Cross-package build orchestration, workspace topo build order, Turbo/Nx pipelines → setup-monorepo-tooling
npm publish,files/publishConfig, provenance, version bump → publish-package-registry- ESLint/Prettier/pre-commit wiring → setup-lint-format-precommit
- Pinning the Node/pnpm/tsc versions themselves (engines,
.nvmrc, Volta) → pin-toolchain-versions
Steps
Pick the bundler by build target — do not default to webpack.
Target Use Why App (SPA/SSR, has an entry HTML or framework) Vite Rollup-based prod build, esbuild dev, HMR, code-splitting out of the box Library (published to npm, consumers bundle it) tsup (esbuild) or Rollup dual ESM+CJS + .d.tsin one config; Rollup when you need fine-grained chunkingNode tool / CLI / serverless fn (single self-run entry) esbuild fastest, bundle deps in, --platform=node, no chunk graph neededLegacy app needing module federation / exotic loaders webpack only when a Vite/Rollup plugin doesn't exist Default: app → Vite, library → tsup, node-tool → esbuild. One tool emits JS;
tscemits types (ortsup --dts/vite-plugin-dtswraps it). Never runtscas the bundler for shipping code — it doesn't bundle, tree-shake, or split.Set the tsconfig essentials —
moduleResolutionis the #1 footgun. Pick the resolution mode by who resolves modules:Scenario modulemoduleResolutionBundler handles resolution (Vite/tsup/esbuild) ESNext(orPreserve)bundlerNode runs the output directly (Node ESM/CJS) NodeNextnodenext// tsconfig.json — app/library baseline { "compilerOptions": { "target": "ES2022", // match your lowest runtime; don't ship ES5 needlessly "lib": ["ES2022", "DOM"], // drop "DOM" for node-only code "module": "ESNext", "moduleResolution": "bundler", "strict": true, "skipLibCheck": true, "esModuleInterop": true, "isolatedModules": true, // required: esbuild/swc compile file-by-file "verbatimModuleSyntax": true,// makes `import type` explicit — kills accidental value imports "declaration": true, // emit .d.ts (libraries) "declarationMap": true, // go-to-definition into your source "sourceMap": true, "outDir": "dist", "paths": { "@/*": ["./src/*"] } } }pathsare a type-level alias only — the bundler must be told too (Viteresolve.alias, tsup/esbuild viavite-tsconfig-paths/esbuildalias, ortsconfig-paths). tsc does not rewrite them in emitted JS.- For a library, emit dual ESM+CJS with a correct
exportsmap — theexportsmap is the contract, file extensions are the proof. tsup config:// tsup.config.ts import { defineConfig } from "tsup"; export default defineConfig({ entry: ["src/index.ts"], format: ["esm", "cjs"], // → index.js (esm) + index.cjs dts: true, // → index.d.ts (+ .d.cts for cjs types) sourcemap: true, treeshake: true, clean: true, target: "node18", external: [/^node:/], // never bundle node builtins });
Keep// package.json — types condition MUST come first in each block { "type": "module", "exports": { ".": { "import": { "types": "./dist/index.d.ts", "default": "./dist/index.js" }, "require": { "types": "./dist/index.d.cts", "default": "./dist/index.cjs" } }, "./package.json": "./package.json" }, "main": "./dist/index.cjs", // legacy fallback for old resolvers "module": "./dist/index.js", "types": "./dist/index.d.ts", "sideEffects": false, "files": ["dist"] }peerDependencies(react, etc.) inexternalso you don't bundle two copies into the consumer. - App: split code with dynamic
import(), then control chunks deliberately. Route-levelconst Page = lazy(() => import('./Page'))andimport('heavy-lib')create async chunks automatically. Pull stable vendor deps into their own long-cached chunk:
Don't over-split (HTTP/2 helps, but hundreds of tiny chunks add request + parse overhead). Split on real route/feature boundaries, not per-file.// vite.config.ts build: { sourcemap: true, rollupOptions: { output: { manualChunks: { vendor: ["react", "react-dom"] }, // or a function for finer control }, }, chunkSizeWarningLimit: 500, } - Enable tree-shaking — it only works on static ESM. Author with
import/export(norequire, nomodule.exports); CJS interop defeats it. Mark the package"sideEffects": false(or list the few files with real side effects, e.g.["**/*.css", "./src/polyfill.ts"]) so the bundler may drop unused modules. Annotate top-level calls that look impure but aren't with/*#__PURE__*/:
Aexport const icon = /*#__PURE__*/ createIcon(path); // droppable if `icon` is unused"sideEffects": falselie (a module that does mutate global state on import) causes silently-missing behavior — list those files. - Inject env at build time via
define/import.meta.env— never bake a secret. Static replacement only:
Anything bundled for the browser is public. Put API keys/DB URLs behind a server route or read them at runtime on the server (// vite: only VITE_* are exposed to client; access via import.meta.env.VITE_API_URL // esbuild/tsup: define: { "process.env.NODE_ENV": JSON.stringify("production") }process.env) — adefine'd secret is grep-able indist/. Gate dev-only code behindif (import.meta.env.DEV)/process.env.NODE_ENV !== "production"so it tree-shakes out of prod. - Always emit sourcemaps; choose by environment.
sourcemap: true(full, external.map) for libraries and CI artifacts. For a public web app, shiphiddensourcemaps (uploaded to your error tracker, not referenced in the bundle) so stack traces de-minify without exposing source to every visitor. Nevereval/inline sourcemaps in production. - Make builds fast and incremental. Use an esbuild/swc transform (Vite and tsup already do) instead of
ts-loader/babelfor the JS transform — 10–100× faster. Keep type-checking out of the bundle path: runtsc --noEmit(orvite build+ a paralleltsc -b --watch) so a type error doesn't block fast iteration but still gates CI. Turn on the persistent cache (Vite caches innode_modules/.vite; fortsc -buseincremental: true+tsBuildInfoFile). Add--metafile(esbuild) /rollup-plugin-visualizerto find what's bloating the bundle. - Verify the output shape before declaring done (see Verify) —
publint+@arethetypeswrong/clicatch the dual-package and types-resolution bugs that don't surface until a consumer installs you.
Common Errors
moduleResolution: node(classic) with modern packages. Fails to resolveexports-map-only packages. Usebundler(bundler resolves) ornodenext(Node resolves) — never the legacynode/node10.typescondition placed last in theexportsmap. TS reads conditions top-down and takes the first match; ifimport/requirecome beforetypes, the consumer gets "no declaration file."typesmust be the first key in each condition block..cjsfile emittingexport {}(or.mjswithrequire). Theexportsmap points at the wrong file per condition, or"type": "module"mismatches the extension. ESM →.js/.mjs, CJS →.cjs. Verify withnode -e "require('your-pkg')"and a separateimport."sideEffects": falseon a package that has side effects. Tree-shaking drops a polyfill/CSS/registration import → feature silently missing in prod only. List the real side-effect files instead of a blanketfalse.- Secret in a
VITE_/defined var. It's inlined into client JS and shipped to every browser. Only public values getVITE_/NEXT_PUBLIC_; secrets stay server-side at runtime. pathsalias resolves in the editor butCannot find module '@/x'at build. tsc/pathsis type-only; the bundler needs its own alias (vite-tsconfig-paths,resolve.alias, ortsconfig-paths). Configure both.isolatedModuleserrors onexport { Foo }whereFoois a type. esbuild/swc compile each file alone and can't tell types from values. Useexport type { Foo }/import type(enforced byverbatimModuleSyntax).- Bundling
peerDependencies(react, etc.) into a library. Consumer gets two React copies → "invalid hook call." Mark peersexternal. - Running
tscas the production bundler. It transpiles per-file but doesn't bundle, tree-shake, split, or rewritepaths— output has unresolved aliases and no chunking. Use a real bundler for JS;tsconly for.d.ts. - No sourcemaps in prod (or inline/eval maps). Minified stack traces are useless; inline maps bloat the bundle and leak source. Emit external (
hiddenfor public web), upload to the error tracker. - Targeting
ES5/oldlibby reflex. Forces heavy down-leveling and polyfills for runtimes that support modern JS. Settarget/libto your actual lowest runtime.
Verify
- Clean build succeeds:
rm -rf dist && <build>exits 0 anddist/contains the expected entry files (.js,.cjs,.d.ts,.map). - Types resolve both ways (library):
npx @arethetypeswrong/cli --packreports no ❌ — no "masquerading as CJS/ESM", no missing types per condition. - Package shape is publishable:
npx publintis clean —exports,main/module/types, and file extensions all consistent. - Dual import actually loads: in a scratch dir,
node -e "import('your-pkg').then(m=>console.log(Object.keys(m)))"andnode -e "console.log(Object.keys(require('your-pkg')))"both print the API — noERR_REQUIRE_ESM/ERR_PACKAGE_PATH_NOT_EXPORTED. - Type-check passes independently:
tsc --noEmitexits 0 (proves the build path didn't skip a type error). - Tree-shaking works: bundle a fixture importing one named export; the visualizer/
--metafileshows unused siblings absent from output. Bundle size drops when an unused heavy import is removed. - Code-splitting present (app): prod build emits ≥1 async chunk per lazy route, and the vendor chunk is separate from app code (check
dist/assets/). - No secret in the bundle:
grep -r "<a known secret substring>" dist/returns nothing; only intended publicVITE_*/NEXT_PUBLIC_*values appear. - Sourcemaps map back: open a built file's
.mapor trigger an error — stack trace points to originalsrc/lines, not minified columns. - Incremental rebuild is fast: a one-line edit triggers a sub-second rebuild (warm cache), not a full cold compile.
Done = clean build emits the correct module formats + types, attw and publint are clean, both import() and require() load the API, tsc --noEmit passes, tree-shaking and code-splitting are confirmed in the output, no secret leaked into dist/, and warm rebuilds are fast.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

