如何在DENO中使用npm模块?

Vinod Sai:

Deno超级酷。我早上看过它,现在想迁移到deno。我试图将现有的nodejs脚本移至deno。谁能帮助我使用deno中的npm模块。我需要esprima模块。这个有包https://github.com/denoland/deno_third_party/tree/master/node_modules,但是我不知道如何使用它。

Marcos Casagrande:

Deno提供了一个节点兼容性库,该将允许使用一些不使用未填充Node.js API的 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))

上面的代码将使用esprimafrom 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" }
]

注意:所使用的许多API std/仍然不稳定,因此您可能需要使用--unstableflag 运行它


尽管由于整个项目已经用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))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章