Deno 提供了一个Node Compatibility Library,这将允许使用一些不使用non-polyfilled Node.js APIs 的 NPM 包。您将能够使用https://deno.land/std/node/module.tsrequire 包
以下作品适用于deno 1.0.0
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))
上面的代码将使用来自node_modules/的esprima。
要运行它,您需要--allow-read 标志
deno run --allow-read 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" }
]
注意:std/ 使用的许多 API 仍然是 unstable,因此您可能需要使用 --unstable 标志运行它。
尽管整个项目已经用 TypeScript 编写,并且没有使用任何依赖项,但他们很容易将其适应 Deno。他们需要做的就是在their imports 上使用.ts 扩展名。
您也可以 fork 项目并进行更改。
// 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!
目前,您可以使用仅使用 Buffer 的软件包,因为您必须包含 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);