Writing

Turning Components Copy-Pasted Across 6 Projects into One npm Package

2026-06-30

8 mins to read

Share article

A hands-on retrospective on taking components that had been copy-pasted across 6 H5 projects, migrating them to Vue 3 + Vant 4, and packaging them as an npm package. The conclusion up front: the component code is simple. The hard part was never the components, but the layer of "engineering contract" that surrounds them.

Opening: the components are simple, and they are not the hard part

When I took this on, I also assumed it was grunt work. Across a dozen or so H5 projects in the acme-* family, components like cascader, select, and dialog had been copy-pasted several times over. Copy them into a new repo, run npm publish, and call it a day, right?

Only once I started did I realize: each component, taken alone, really is simple (a thin wrapper around Vant plus some styling), but "turning it into a package that other people can safely depend on" hides a pile of pitfalls the compiler will never report for you. Below are the ones I think are most worth explaining in depth.

1. What can be extracted and what can't: look at coupling, not complexity

My first instinct was "extract the simple ones first". Wrong. What decides whether a component can be extracted cleanly is its dependency graph, not its line count.

  • cascader is 260 lines with complicated logic, but it depends only on Vant → easy to extract.
  • city-search is a simple search box, yet it does import { queryCityList } from '@/api' → hard to extract.

A library component cannot assume the host has some @/api. The fix is dependency inversion: push "fetching the data" out of the component. There are three ways to do it, and the trade-off is "who owns loading / caching / error handling":

data prop   : host fetches data and passes it in        → purest component, most work for the host
fetcher     : pass the fetch function in as a prop      → flexible, but couples the call timing
emit event  : component emits @search, host fills data  → decoupled interaction, usually the best

Takeaway: to judge "can this become a library", draw the dependency graph first. Visual complexity will fool you; coupling won't.

2. A pitfall that "compiles but doesn't run"

This was the most valuable lesson of the whole exercise. Vant 4 removed DatetimePicker (it was split into DatePicker). Without thinking, I wrote:

import { DatetimePicker } from 'vant'   // in Vant 4, this is undefined

vite build went green. TypeScript didn't complain, esbuild didn't complain, nothing said a word. Only when the component rendered in the browser did a [Vue warn]: Failed to resolve component show up.

Why can't the build catch it? Because Vue resolves components at runtime. The template <van-datetime-picker> is compiled into resolveComponent("van-datetime-picker"), a call that looks up the component registry by string name at runtime. The import yielding undefined is perfectly legal as far as JS is concerned (you have merely registered a local component whose value is undefined). The warning only appears when rendering actually happens and the lookup fails.

// What the compiled template looks like (simplified)
const _component_van_datetime_picker = resolveComponent("van-datetime-picker")
// import is undefined → not found in the registry → warns only at runtime, silent at compile time

Takeaway: "the build is green" is the weakest guarantee there is. For a major framework upgrade you must read the migration guide, check for removed / renamed APIs, and use "export-name existence checks + real rendering" to cover the blind spots the compiler can't.

3. Migrating v-model: one component is both consumer and provider

The v-model contract changed completely from Vue 2 to 3: value + @input → modelValue + update:modelValue; .sync → v-model:x. On top of that, Vant 4 changed Popup/Dialog visibility from v-model to v-model:show.

The key point: our Dialog component is, on the inside, a v-model consumer of van-dialog, and on the outside, a v-model provider to the host. Both ends have to change together, with a watch in the middle passing values through in both directions:

<van-dialog v-model:show="isShow">…</van-dialog>
<script>
export default {
  props: { modelValue: { type: Boolean, default: false } },
  emits: ['update:modelValue'],
  watch: {
    modelValue(v){ this.isShow = v },                                  // host → internal
    isShow(v){ if (v !== this.modelValue) this.$emit('update:modelValue', v) }, // internal → host
  },
}
</script>

For popup-based components such as the cascader and date picker, I used a computed with get/set to pass the host's modelValue straight through to v-model:show, which is cleaner.

4. A library is, in essence, an "anti-corruption layer"

DatePicker illustrates this best. In Vant 4 its v-model data changed from a Date to an array of strings, ['2024','06','30']. If I passed that change through, every consumer would have to change too, and the library would become nothing more than "a relay for upstream breaking changes", with no value at all.

So I had the component adapt to the new format internally, while still accepting / emitting Date externally:

// In:  Date → ['Y','M','D'] fed to Vant 4
// Out: string[] from confirm → converted back to Date and emitted to the host
confirm({ selectedValues }){
  const [y,m,d] = selectedValues
  this.$emit('select', new Date(+y, +m - 1, +d))
}

Takeaway: the value of a library = absorbing upstream churn internally and giving consumers a stable external contract. This is what the anti-corruption layer that backend engineers talk about looks like in a frontend component library. Swap the internals as much as you like; the public API has to stay stable.

5. peerDependencies and the "two Vues" disaster

Many people think vue / vant go into peerDependencies "to reduce bundle size". That is only a side effect. The real reason is that the framework must be a singleton.

If the library puts vue in dependencies and bundles it into its output, the host project ends up with two Vue runtimes. The consequence is not "wasted bytes" but functional breakage:

  • There are two reactivity systems, and provide / inject does not work across instances;
  • app.use(Vant) registers on the host's app instance, while your components run on the copy of Vue bundled with the library → components can't be found and injections come back empty;
  • In the React world this disease is called Invalid hook call: multiple copies of react each have their own dispatcher, and hooks simply crash.

This is also why debugging a component library with npm link so often blows up: the symlink makes the library resolve the Vue/React in its own node_modules, and instantly you have two instances. The fix is peerDeps + marking them external at build time + letting the host provide the one and only copy (or, for local debugging, using yalc or configuring resolve.dedupe).

// vite.config: externalize the peers so the output never contains vue/vant
rollupOptions: { external: ['vue', 'vant'] }

6. You think you are publishing components; you are actually publishing a "contract"

Application projects almost never touch these package.json fields, but for a library they are the public interface definition:

  • exports: the authoritative entry point for modern resolution, taking precedence over main/module. It also has an underrated role, sealing off subpaths: files not listed in exports simply cannot be imported by consumers, which effectively enforces the encapsulation boundary. (When writing a TS library, also note that the types condition must come first, otherwise type resolution falls through.)
  • sideEffects: declares which modules have side effects. In a component library, import './x.css' is a side effect. If you take the lazy route and write "sideEffects": false, the bundler will decide that this CSS is "unused" and tree-shake it away, and all your styles vanish. The correct form is "sideEffects": ["**/*.css"].
  • files: the publish allowlist. Use an allowlist (["dist"]) rather than a .npmignore denylist: when you miss something, the consequence is "a file was left out" rather than "source code / secrets were published by mistake".

Then there are assets: the local images referenced by cascader have to travel with the package. Let Vite automatically inline small images (under 4KB) into the output as base64; otherwise what you ship is a runtime 404.

7. Four lines of defense: how to confirm it "really works"

Since "the build is green" can't be trusted, I verify in four layers, each catching a different kind of bug:

① npm run build                      → template / syntax compile errors
② check vant export names with node  → runtime component resolution errors (the build can't catch these)
③ npm pack + tar -tf                 → missing / accidentally published files
④ install the .tgz in a fresh project, then build → whether the exports map and peerDeps actually install

Layer ④ is especially critical: it is the only way to verify that "the exports field, the @scope/style.css subpath, and the peerDeps" hold up from a real consumer's point of view. The source projects are all Vue 2 and can't install this Vue 3 package, so I spun up a brand-new Vue 3 project specifically to install the .tgz and get it running.

8. Publishing: risk-free practice with Verdaccio

An internal library should not be published to public npm (the code becomes public and is almost impossible to take back). I used Verdaccio to run a local private registry and walk through the whole flow: the @acme scope is routed to localhost:4873 via .npmrc, while all other dependencies still go to the public registry.

@acme:registry=http://localhost:4873/

Once that works, moving to the team's private registry (such as Azure Artifacts or Nexus) only means changing this one registry URL and the token; the commands are exactly the same. Verdaccio is a good choice for practice and for offline caching in CI.

Wrapping up: a transferable methodology

Looking back, none of what I really learned here is tied to Vant:

  1. Extract based on coupling, not complexity, and decouple with dependency inversion;
  2. Framework migrations have "silent at compile time" pitfalls, and a green build is the weakest guarantee;
  3. A library is in essence an anti-corruption layer, and its external contract must be stable;
  4. peerDeps exist for the framework singleton, not for smaller bundles;
  5. package.json is a public interface, and exports / sideEffects / files each deserve care;
  6. Replace "I think it's fine" with layered verification.

Component logic is the "algorithm"; these things are the "engineering". Swap in a React component library, or even wrap an LLM tool SDK as an npm package someday, and the playbook is exactly the same. This is what separates "can write components" from "can deliver reusable assets".