Deno 提供了一个节点兼容库,这允许使用一些不使用的 NPM 包非 Polyfill Node.js API.
As of 德诺 1.25有一个实验性 NPM 支持通过使用npm:
说明符
npm:<package-name>[@<version-requirement>][/<sub-path>]
import express from "npm:express";
const app = express();
app.get("/", function (req, res) {
res.send("Hello World");
});
app.listen(3000);
console.log("listening on http://localhost:3000/");
The --unstable
标志是必需的。
执行此操作时,不npm install
是必要的并且没有node_modules
文件夹已创建
你也可以require
并使用安装了 npm 包https://deno.land/std/node/module.ts
以下作品适用于deno >= 1.0.0
npm install esprima
import { createRequire } from "https://deno.land/std/node/module.ts";
const require = createRequire(import.meta.url);
const esprima = require("esprima");
const program = 'const answer = 42';
console.log(esprima.tokenize(program))
上面的代码将使用esprima
from node_modules/
.
要运行它,您需要--allow-read
&&--allow-env
flag
# you can also use --allow-all
deno run --allow-read --allow-env esprima.js
您可以将其限制为仅node_modules
deno run --allow-read=node_modules esprima.js
哪个输出:
[
{ type: "Keyword", value: "const" },
{ type: "Identifier", value: "answer" },
{ type: "Punctuator", value: "=" },
{ type: "Numeric", value: "42" }
]
Note:使用的许多APIstd/
仍unstable,所以你可能需要运行它--unstable
flag.
尽管整个项目已经用 TypeScript 编写,并且没有使用任何依赖项,但他们很容易将其适应 Deno。他们所需要做的就是使用.ts
扩展于他们的进口。
您还可以分叉该项目并进行更改。
// import { CommentHandler } from './comment-handler';
import { CommentHandler } from './comment-handler.ts';
// ...
一旦他们这样做了,你就可以做:
// Ideally they would issue a tagged release and you'll use that instead of master
import esprima from 'https://raw.githubusercontent.com/jquery/esprima/master/src/esprima.ts';
const program = 'const answer = 42';
console.log(esprima.tokenize(program))
选择
您还可以使用https://jspm.io/
它将把 NPM 模块转换为 ES 模块
npm 上的所有模块都转换为处理完整的 ES 模块
CommonJS 兼容性,包括严格的模式转换。
import esprima from "https://dev.jspm.io/esprima";
const program = 'const answer = 42';
console.log(esprima.tokenize(program))
对于使用 jspm 不支持的 Node.js 模块的包,它将抛出错误:
Uncaught Error: Node.js fs module is not supported by jspm core.
Deno support here is tracking in
https://github.com/jspm/jspm-core/issues/4, +1's are appreciated!
要填充这些 Node.js API,您必须包含std/node
.
// import so polyfilled Buffer is exposed
import "https://deno.land/std/node/module.ts";
import BJSON from 'https://dev.jspm.io/buffer-json';
const str = BJSON.stringify({ buf: Buffer.from('hello') })
console.log(str);