德诺超级酷.我早上看到的,现在想迁移到德诺.我的脚本试图移动.有谁能帮助我在deno中使用npm模块吗.我需要一个模块.这个有https://github.com/denoland/deno_third_party/tree/master/node_modules个包裹,但我不知道如何使用.

推荐答案

Deno提供了一个Node Compatibility Library,这将允许使用一些不使用non-polyfilled Node.js APIs的NPM包.你可以用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))

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

Note:std/使用的许多API仍然是unstable,所以您可能需要使用--unstable标志运行它.


虽然整个项目都是用TypeScript编写的,而且没有使用任何依赖项,但他们很容易将其应用到Deno中.他们所需要做的就是在their imports上使用.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模块,以处理完整的数据

import esprima from "https://dev.jspm.io/esprima";

const program = 'const answer = 42';
console.log(esprima.tokenize(program))

对于使用Node的包.jspm不支持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);

Node.js相关问答推荐

如何在node.js中以随机顺序调用函数并按顺序操作

使用HTTPS从NodeJS 17.9.1升级到18.0.0后,SignalR连接失败

如何在MongoDB中更新嵌套数组

设置默认 node 版本

如何使用NodeJS在mongodb中更新文档

无法通过 NextJS 访问 HTTP 帖子中的正文

yarn 安装失败,因为 node-gyp 正在寻找过时的 node 版本标头

如何使用 Jest 模拟异步函数的延迟时间

[NodeJs 从 ADAL 升级到 MSAL]:无法在字符串上创建属性authenticationScheme

为什么需要在 NodeJS 应用程序中创建服务器?

try 运行迁移时的 Typeorm:缺少必需的参数:dataSource

如何限制 cron 表单将消息推送到 RabbitMQ?

如何在 Node.js 的 console.log() 中创建换行符

Base64 编码一个 javascript 对象

在多个 .env 文件之间切换,例如 .env.development 和 node.js

Express.js:没有这样的文件或目录

npm 出现无法读取依赖项错误

在单独的模块中定义 Mongoose 模型

使用 Mongoose 进行多对多映射

node --experimental-modules,请求的模块不提供名为的导出