Skip to content

Latest commit

 

History

History
369 lines (263 loc) · 20.2 KB

3.develop-and-publish.md

File metadata and controls

369 lines (263 loc) · 20.2 KB
title Develop and Publish
description Prepare a checkout, work on the module in its playground, and publish it to npm.

A module has a script for each stage of its life: preparing a fresh checkout, running the playground, and publishing a release. This page describes what each script does, and the two development setups that they depend on.

To create a module from the starter, see Getting Started. To move a module that used stub builds in v1, see Stub builds in the upgrade guide.

Preparing a checkout

The playground installs the module by its package name, so it loads whatever package.json points at. The package manager that publishes your module decides which setup you use:

Package manager package.json points at While you develop
pnpm, Yarn 4 Your sources, with the dist paths in publishConfig The playground runs your sources. See Source exports.
npm, Yarn 3 and earlier, bun dist tsdown --watch rebuilds dist. See Developing against dist.

In both setups, the playground's package.json installs the module in a way that depends on the package manager. See Installing the module in the playground.

Run dev:prepare after you install dependencies. Run it again when the types that it generates are out of date, such as after the module registers a new template or server route. The module's own app, server and shared type checks see the types of module code as of the last prepare.

The build runs prepare on its own when .nuxt is missing. Keep prepare in dev:prepare anyway, so the module's types are in place before your editor or your type check needs them.

The playground needs .nuxt too: Vite reads the module's tsconfig.json when it transforms the module's TypeScript files, and that file references the tsconfigs in .nuxt. Until prepare has generated them, nuxt dev playground responds to every request with a 500 error, [TSCONFIG_ERROR] Failed to load tsconfig '.nuxt/tsconfig.node.json'. The dev script runs nuxt-module-build prepare before nuxt dev playground, so it also works in a fresh checkout.

Source exports

pnpm and Yarn 4 publish the fields of publishConfig in place of the top-level ones. With either of them, point exports and main at src, and the same fields in publishConfig at dist:

{
  "exports": {
    ".": {
      "types": "./.nuxt/module-builder/types.d.mts",
      "import": "./src/module.ts"
    }
  },
  "main": "./src/module.ts",
  "files": [
    "dist"
  ],
  "publishConfig": {
    "exports": {
      ".": {
        "types": "./dist/types.d.mts",
        "import": "./dist/module.mjs"
      }
    },
    "main": "./dist/module.mjs"
  },
  "scripts": {
    "dev": "nuxt-module-build prepare && nuxt dev playground",
    "dev:prepare": "nuxt-module-build prepare && nuxt prepare playground",
    "prepack": "tsdown"
  }
}

dev:prepare runs two commands:

  1. nuxt-module-build prepare generates the module's own .nuxt, for the module's tsconfig.json. It also writes the .nuxt/module-builder/types.d.mts that the root export's types condition points at. See prepare.
  2. nuxt prepare playground generates the playground's .nuxt. It loads src/module.ts through exports.

publishConfig replaces each field as a whole, so publishConfig.exports repeats every subpath and condition of exports. Exports shows an example with subpaths.

The playground has to resolve the module's name to the module directory itself, as Installing the module in the playground describes.

The playground's type check includes your sources and the files that they import types from. The playground's tsconfig.json lists the errors that this can report.

A module that keeps typesVersions for node10 consumers leaves it at the top level, pointing at dist, with pnpm and with Yarn 4. TypeScript only reads it for a package whose exports it doesn't read, as under node10 module resolution, which a playground doesn't use. pnpm also applies publishConfig.typesVersions, but Yarn 4 packs typesVersions as written.

Code that reaches into dist

There is no dist while you develop, so code that reaches into dist by path has to point at src. Resolve runtime files relative to src/module.ts, without an extension:

import { addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  meta: { name: 'my-module', configKey: 'myModule' },
  setup() {
    const resolver = createResolver(import.meta.url)

    addPlugin(resolver.resolve('./runtime/app/plugins/greeting'))
  },
})

The build keeps the layout of src in dist, and Nuxt adds the extension.

Build-time code that reads a runtime file's contents, such as code that inlines the file into a template, needs more care. It finds no file at the path without an extension, and TypeScript at the .ts path. Generate the template from code that doesn't depend on the built file:

import { addTemplate, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  meta: { name: 'my-module', configKey: 'myModule' },
  defaults: { languages: ['ts', 'vue'] },
  setup(options) {
    addTemplate({
      filename: 'my-module/languages.mjs',
      getContents: () => `export const languages = ${JSON.stringify(options.languages)}`,
    })
  },
})

If the template has to contain the built file, build dist first and keep reading from dist.

Developing against dist

npm, Yarn 3 and earlier, and bun publish some or all of these fields as written. With them, point package.json at dist, and build dist before the playground is prepared:

{
  "exports": {
    ".": {
      "types": "./dist/types.d.mts",
      "import": "./dist/module.mjs"
    }
  },
  "main": "./dist/module.mjs",
  "files": [
    "dist"
  ],
  "scripts": {
    "dev": "nuxt-module-build prepare && nuxt dev playground",
    "dev:prepare": "nuxt-module-build prepare && tsdown && nuxt prepare playground",
    "prepack": "tsdown"
  }
}

dev:prepare runs three commands:

  1. nuxt-module-build prepare generates the module's own .nuxt, for the module's tsconfig.json.
  2. tsdown builds dist. See tsdown.
  3. nuxt prepare playground generates the playground's .nuxt. It loads dist/module.mjs through exports.

The playground installs the module as Installing the module in the playground describes.

While the playground runs, run tsdown --watch next to it:

npx tsdown --watch

Watch mode keeps dist in place while its first build runs, so you can start both at the same time. Each change under src rebuilds dist, and a rebuild only writes the files whose content changed.

Other nuxt prepare commands

nuxt-module-build prepare installs the module from its sources, even where the module's own .nuxtrc or nuxt.config lists it by name. Any other nuxt prepare that loads the module by name loads it from dist, and leaves the module out when dist is missing. One example is a nuxt prepare at the repository root, with modules[]=my-module in its .nuxtrc. Run tsdown before such a command:

{
  "scripts": {
    "dev:prepare": "nuxt-module-build prepare && tsdown && nuxt prepare && nuxt prepare playground"
  }
}

Installing the module in the playground

The playground's package.json installs the module from the module directory, under the name that the playground's nuxt.config lists. The package manager decides how, in both setups:

Package manager Workspace my-module in playground/package.json
pnpm playground in packages of pnpm-workspace.yaml link:..
Yarn 4 playground in the root workspaces link:..
bun playground in the root workspaces link:..
npm playground in the root workspaces file:..
Yarn 1 None: run yarn install in playground as well link:..
{
  "name": "my-module-playground",
  "private": true,
  "type": "module",
  "dependencies": {
    "my-module": "link:.."
  }
}
  • link:.. links the module directory, whatever the name in its package.json. workspace:* works with pnpm, Yarn 4 and bun too, but only while the dependency's name matches that name.
  • bun installs a workspace only when its package.json has a name.
  • npm doesn't support link:. Yarn copies a file:.. dependency when it installs it, so the playground doesn't see later changes, or a dist built after the install.
  • Yarn 1 enables workspaces only in a private package, so the root of a published module can't list them.
  • With Yarn 3, none of these links the module directory.

With pnpm, also list the dependencies that have build scripts in allowBuilds:

packages:
  - playground

allowBuilds:
  esbuild: false

pnpm 11 and later fail the install while a dependency with a build script is missing from allowBuilds. pnpm approve-builds adds the missing ones: true runs the script, and false skips it. pnpm 10 skips them with a warning.

A playground that lists the module by relative path, as modules: ['../src/module'], loads src/module.ts without the dependency, so it works the same with every package manager, in both setups. Its type check doesn't see the module's type augmentations. See playground/.

Working in the playground

The playground is a Nuxt app that installs your module, so you can try the module as you change it:

  • The dev script runs nuxt-module-build prepare, then starts the playground's development server with nuxt dev playground.
  • nuxt build playground builds the playground.
  • Any other nuxt command works against the playground too, as nuxt <command> playground.

Nuxt serves the files of the runtime directory through Vite. An edited component updates in place, and an edited plugin reloads the page. When the playground runs dist, this happens after tsdown --watch rebuilds the file.

The playground loads the module itself once, when nuxt dev starts. Restart nuxt dev after you change src/module.ts or the files that it imports.

With source exports, the playground always runs your sources. When package.json points at dist, the playground runs the last build. To try a full build there, build the module and start the playground:

npx tsdown && npx nuxt dev playground

For the module's tests, see Testing in the Module Author Guide.

Publishing

The prepack script runs tsdown, so the package manager builds the module whenever it packs or publishes it. You don't need to build the module yourself first.

Before your first release, create an account on npmjs.com and log in with npm login.

Checking the package

To check the package before you publish it, follow these steps:

  1. Pack the module with the package manager that publishes it, such as pnpm pack for source exports:

    pnpm pack
  2. Run publint on the tarball:

    npx publint ./my-module-1.0.0.tgz
  3. List the imports in the declarations that don't resolve from the package alone, with Are the Types Wrong?, and the number of files that each appears in. Write its report to a file, and read the file with jq. The first command exits with 1 whenever the report lists a problem:

    npx @arethetypeswrong/cli ./my-module-1.0.0.tgz --profile esm-only --format json > attw.json
    jq -r '.analysis.problems[] | select(.kind == "InternalResolutionError" and .resolutionOption != "node10") | "\(.moduleSpecifier) \(.fileName)"' attw.json | sort -u | cut -d' ' -f1 | uniq -c

    Each one has to be an alias that only a Nuxt app provides, such as #app, #imports, #build/my-module/options, or an alias that the module adds to the app. The command leaves out node10, which the esm-only profile doesn't check either. Under node10, a module without typesVersions also can't resolve its own imports and subpaths, such as my-module/utils in dist/runtime/types.d.ts. A module that supports node10 consumers imports those files by relative path in the code that the declarations come from. To list the node10 problems of such a module, run the command with == "node10" in place of != "node10": an import of the module's own imports entry, such as #internal, appears only there. Fix any other, such as a relative import of a file that the package doesn't contain. An app's nuxt.config.ts context reads the module's options type without the app's aliases, and types an alias that doesn't resolve as any, so move a type that the options type takes from such a file into one that doesn't import the aliases.

  4. Run Are the Types Wrong? with those imports ignored:

    npx @arethetypeswrong/cli ./my-module-1.0.0.tgz --profile esm-only --ignore-rules internal-resolution-error

    The esm-only profile leaves out node10 resolution, and require under node16, which can't load an ES module. A module that sets types and typesVersions for node10 consumers checks node10 too, with --ignore-rules cjs-resolves-to-esm internal-resolution-error, no --profile, and no .attw.json that sets profile or ignoreRules: every profile but strict marks the node10 resolutions ignored, and a config's ignoreRules are added to the command's, so either one hides a node10 failure from both the table and the exit code. Read the node10 row too: with the types and the imports inside an import condition, require resolves nothing, so the node16 (from CJS) row reports NoResolution, and the only rule that hides it, no-resolution, hides node10 as well.

For a module that is correct, Are the Types Wrong? reports three kinds of problem, which these steps leave out:

  • CJSResolvesToESM, under node16 from CommonJS. The module is an ES module, which require can't load.
  • NoResolution, under node10, for each subpath export of a module without typesVersions.
  • InternalResolutionError, for an import in a declaration file that only a Nuxt app resolves. It appears under every resolution for aliases such as #imports and #build/*, and under node10 for the package's own imports. The esm-only profile doesn't leave it out, so step 4 ignores the rule.

attw --pack . packs with npm, which fails on a package with devEngines, and on source exports with NUXT_MB_C0104. Pack the module with its own package manager first, as in this script:

{
  "scripts": {
    "test:attw": "pnpm pack --out node_modules/.cache/attw.tgz && pnpm dlx @arethetypeswrong/cli node_modules/.cache/attw.tgz --profile esm-only --ignore-rules internal-resolution-error"
  }
}

With @arethetypeswrong/cli in devDependencies, write attw in place of pnpm dlx @arethetypeswrong/cli.

tsdown's own attw option packs the module with its package manager and checks the tarball after each build. It needs @arethetypeswrong/core in the module's devDependencies:

pnpm add -D @arethetypeswrong/core

Its ignoreRules takes the same rules as --ignore-rules. Once step 3 shows that every import that doesn't resolve is a Nuxt alias, set it as in step 4:

import { builder } from '@nuxt/module-builder/tsdown'
import { defineConfig } from 'tsdown'

export default defineConfig({
  attw: { level: 'error', profile: 'esm-only', ignoreRules: ['internal-resolution-error'] },
  plugins: [builder()],
})

With Yarn 2 or later, yarn pack runs the prepack script, and tsdown can't turn that off. When prepack runs tsdown, each build then packs and builds again. Check the package with steps 1 to 4 instead.

Releasing a version

A release script can publish a new version in one step. Use the package manager that applies your setup:

::code-group

{
  "scripts": {
    "release": "pnpm lint && pnpm test && pnpm prepack && changelogen --release && pnpm publish && git push --follow-tags"
  }
}
{
  "scripts": {
    "release": "npm run lint && npm run test && npm run prepack && changelogen --release && npm publish && git push --follow-tags"
  }
}

::

The script runs these steps:

  1. Run the linter, the tests, and the build. The release stops if any of them fails, before changelogen commits and tags a new version.
  2. Run changelogen --release, which bumps the version, updates CHANGELOG.md from your commit messages, and commits and tags the result.
  3. Publish the package. prepack builds the module again, so dist has the new version.
  4. Push the release commit and its tag with git push --follow-tags.

Commit your changes before you run release. changelogen reads Conventional Commits to choose the version bump and to write the changelog.

With source exports, publish with pnpm publish or yarn npm publish. A release script that runs npm publish fails, even when pnpm run starts it. npm publish of a tarball that pnpm pack wrote works, because its package.json already has the dist paths, and the build doesn't run again.

Checks on published paths

Every build reads the path fields of package.json, such as exports, main, and types. It reads them with the fields of publishConfig in place of the top-level ones. The build fails before it starts when one of them points at a path that doesn't work once the package is installed:

  • A TypeScript source other than a declaration, which Node doesn't load from node_modules.
  • A path that the pack leaves out, because files doesn't list it. Without files, a path into .nuxt counts as left out.

Every pack includes package.json and the file that main points at, so files doesn't have to list them. To publish a file other than a TypeScript source as it is, list it in files:

{
  "files": ["dist", ".nuxt/my-module.css"],
  "imports": {
    "#my-module/styles.css": "./.nuxt/my-module.css"
  }
}

The build checks an entry of imports in the same way once the build is done, and only when the build output imports it. An entry that the build bundles into module.mjs can keep pointing at src.

Checks when you pack

When tsdown or nuxt-module-build build runs as the prepack or prepublishOnly script, the build also checks how the package manager packs package.json. It fails when the package manager would publish a path that points at your sources:

  • The package manager has to apply publishConfig to each field that points at your sources. pnpm applies it to all of them. Yarn 4 applies it to every field except typesVersions. Yarn 3 applies it to exports, imports, main, and module, and Yarn 2 to main and module. npm, Yarn 1, and bun pack package.json as written.
  • publishConfig has to set each of those fields, to paths that pass the checks on published paths.

The build reads the package manager from the npm_config_user_agent and npm_execpath environment variables. It reads the script name from npm_lifecycle_event. bun pm pack and bun publish started from a pnpm or Yarn 4 script inherit that script's variables, so the build reads them as pnpm or Yarn.

A prepack script that runs another script, such as "prepack": "npm run build", isn't checked, because the nested script runs as build. Run tsdown or nuxt-module-build build from prepack directly. prepack can run other commands after it, such as "prepack": "tsdown && pnpm build:client", and is still checked.

After the build, a warning lists the paths in package.json that the build didn't produce.