denoland / dnt

Deno to npm package build tool.
MIT License
1.25k stars 40 forks source link

Specifying peer dependency on NPM package does not work #433

Open joeftiger opened 1 month ago

joeftiger commented 1 month ago

Hello

I noticed that NPM imports inside deno.json cannot be specified as a peer dependency using @deno/dnt and always end up inside dependencies. When specifying the import using esm.sh/ it works, however.

Minimal example using Blockly as dependency:

deno.json:

{
  "exports": {
    ".": "./mod.ts"
  },
  "imports": {
    "@deno/dnt": "jsr:@deno/dnt@^0.41.3",
    "blockly": "npm:blockly@^11.1.1"
    // "blockly": "https://esm.sh/blockly@^11.1.1"
  }
}

mod.ts:

import "blockly";

build_npm.ts:

import { build, emptyDir } from "@deno/dnt";

await emptyDir("./npm");

await build({
  entryPoints: ["./mod.ts"],
  outDir: "./npm",
  shims: {
    deno: true,
  },
  typeCheck: "both",
  mappings: {
    "npm:blockly@^11.1.1": {
    // "https://esm.sh/blockly@^11.1.1": {
      name: "blockly",
      version: "^11.1.1",
      peerDependency: true,
    },
  },
  package: {
    name: "pure-deno",
    version: "0.0.1",
  },
  importMap: "./deno.json",
});

Replacing the import with the esm.sh/ version correctly transforms blockly as peer dependency while using the npm: version keeps it as direct dependency.

As a workaround one has to keep a separate import map or manually specify dependencies inside package in the build script.

joeftiger commented 1 month ago

If anyone is running into the same problem right now, my current workaround is the following code snippet to (dirtily) cut out peer dependencies:

const importMap = JSON.parse(Deno.readTextFileSync("./deno.json"));
const blocklyVersion = (<string>importMap["imports"]["blockly"]).split("@")[1];
delete importMap["imports"]["blockly"];
Deno.writeTextFileSync("./deno-npm.json", JSON.stringify(importMap, null, 2));

/// ...
await build({
  // ...
  package: {
    // ...
    peerDependencies: {
      blockly: blocklyVersion,
    },
  },
  importMap: "./deno-npm.json",
});