Developing an NPM package with Deno
To convert a Deno module to an npm package using dnt (Deno to Node Transform), follow these steps:
- Create a build script:
First, create a build script (e.g.,
build_npm.ts) in your project directory. This script will use dnt to transform your Deno module into an npm package.
1import { build, emptyDir } from "https://deno.land/x/dnt@0.37.0/mod.ts";2
3await emptyDir("./npm");4
5await build({6 entryPoints: ["./mod.ts"],7 outDir: "./npm",8 shims: {9 deno: true,10 },11 package: {12 name: "your-package-name",13 version: Deno.args[0],14 description: "Your package description",15 license: "MIT",16 repository: {17 type: "git",18 url: "git+https://github.com/yourusername/your-repo.git",19 },20 bugs: {21 url: "https://github.com/yourusername/your-repo/issues",22 },23 },24 postBuild() {25 Deno.copyFileSync("LICENSE", "npm/LICENSE");26 Deno.copyFileSync("README.md", "npm/README.md");27 },28});- Run the build script: Execute the build script using Deno, providing the version number as an argument:
1deno run -A build_npm.ts 1.0.0This command will:
- Transform your Deno code to Node.js compatible code
- Generate both ESM and CommonJS versions
- Create TypeScript declaration files
- Run tests in both Deno and Node.js environments
- Generate a
package.jsonfile[1][2][4]
- Publish to npm: After the build process completes, you can publish your package to npm:
1cd npm2npm publishKey points to remember:
- dnt handles the transformation of Deno-specific APIs and module specifiers to make them compatible with Node.js[1][3].
- It generates both ESM and CommonJS versions of your package, ensuring compatibility with different Node.js environments[4].
- The build process includes running tests in both Deno and Node.js environments to ensure compatibility[1][4].
- You can customize the build process, including adding shims for specific Deno APIs, mapping specifiers to npm packages, and more[3].
By following these steps, you can easily convert your Deno module into an npm package that works in Node.js while maintaining compatibility with Deno, allowing you to reach a wider audience of developers[2][4].
Citations:
[1] https://deno.com/blog/dnt-oak
[2] https://deno.com/learn/modules
[3] https://github.com/denoland/dnt
[4] https://deno.com/blog/publish-esm-cjs-module-dnt
[5] https://stackoverflow.com/questions/75186363/how-to-import-a-deno-library-into-a-node-project
[6] https://docs.deno.com/examples/npm/
[7] https://docs.deno.com/runtime/fundamentals/node/
[8] https://www.npmjs.com/package/deno-bin