javascript - 如何在 DENO 中使用 npm 模块?

标签 javascript node.js npm esprima deno

德诺 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。他们需要做的就是使用.tstheir 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/

相关文章:

node.js - 我怎样才能从运行 gulp 的地方获得路径?

npm - 如何将贡献者(合作者)添加到 npm 包中?

javascript - 使用 grunt : Object Gruntfile. 得到一个奇怪的错误 js has no method 'flatten'

javascript - 我如何使用表行 id 作为 angularjs 函数的参数

javascript - 动态表行创建

javascript - 如何从 Meteor.js 中方法内部的方法返回错误

node.js - 使用 express 提供静态文件时无法使用基本身份验证

javascript - 在 JavaScript 中限制浮点精度

node.js - 如何将 postman 的数据发布到 Output.json 文件?

node.js - 如何在 Windows 7 中删除 git 本地存储库文件夹