Building modules with Deno
Why Deno?
Writing and publishing modern JavaScript modules today can be painful. As a module author, your module should support CommonJS, ESM, and TypeScript declarations, as well as work in Deno, Node.js, and web browsers.
With Deno, writing your module is straightforward and can support all of the targets and formats needed to support the widest range of module users. The best part is that you can be productive immediately without needing to configure your toolchain or setup TypeScript.
dnt
— Deno to Node transform
Once you have created your modern ES module, you can use
dnt
to transform your module into an npm
module that: Supports CommonJS and ESM Runs test in both Deno and Node Supports
TypeScript Works in both Deno, Node, and the browser
Here’s
a sample dnt
build script
for a module called is-42
:
import { build, emptyDir } from "https://deno.land/x/dnt@0.37.0/mod.ts";
await emptyDir("./npm");
await build({
entryPoints: ["./mod.ts"],
outDir: "./npm",
shims: {
deno: true,
},
package: {
name: "is-42",
version: Deno.args[0],
description:
"Boolean function that returns whether or not parameter is the number 42",
license: "MIT",
repository: {
type: "git",
url: "git+https://github.com/lambtron/is-42.git",
},
bugs: {
url: "https://github.com/lambtron/is-42/issues",
},
},
postBuild() {
Deno.copyFileSync("LICENSE", "npm/LICENSE");
Deno.copyFileSync("README.md", "npm/README.md");
},
});
To run the build script:
$ deno run -A build_npm.ts 0.0.1
And its output:
[dnt] Transforming...
[dnt] Running npm install...
added 6 packages, and audited 7 packages in 2s
found 0 vulnerabilities
[dnt] Building project...
[dnt] Type checking ESM...
[dnt] Emitting ESM package...
[dnt] Emitting script package...
[dnt] Running post build action...
[dnt] Running tests...
> test
> node test_runner.js
Running tests in ./script/mod_test.js...
test 42 should return true ... ok
test 1 should return false ... ok
Running tests in ./esm/mod_test.js...
test 42 should return true ... ok
test 1 should return false ... ok
[dnt] Complete!
The CommonJS and ESM npm compatible packages are now in /npm, so publishing to npm requires only this step:
$ npm publish /npm
Additional Resources
Here are some examples, blog posts, and videos about using Deno to create JavaScript modules.