德诺 super 酷。早上看到了,现在想迁移到deno。我试图将我现有的 nodejs 脚本移动到 deno。任何人都可以帮助我了解如何在 deno 中使用 npm 模块。我需要 esprima 模块。这个有包https://github.com/denoland/deno_third_party/tree/master/node_modules但我无法弄清楚如何使用它。
最佳答案
Deno 提供 Node Compatibility Library ,这将允许使用一些不使用 non-polyfilled Node.js APIs 的 NPM 包.您将能够 require
使用 https://deno.land/std/node/module.ts
的包
以下作品适用于 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))
上面的代码将使用 esprima
来自 node_modules/
.要运行它,您需要
--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。他们需要做的就是使用
.ts
在 their imports 上扩展.您还可以 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 模块All modules on npm are converted into ES modules handling full CommonJS compatibility including strict mode conversions.
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);
关于javascript - 如何在 DENO 中使用 npm 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61821038/