Deno的诞生过程中,有个因素是为了抛掉 node_modules
的历史问题,但是不可避免的会带来暂时无法利用 npm
生态的遗憾。毕竟npm
沉淀了10余年的JS
生态,如果直接放弃是有点遗憾的。目前(截至2020年5月),Deno
的官方标准库 deno/std
在建设对 Node.js
的兼容 deno/std/node,这也对后续能否利用 npm
生态带来曙光。
至于目前 Deno
暂时无法直接使用 npm
生态,我们可以换种方式间接去使用,本篇是主要探讨如何在 Deno
环境里,借助 jspm
调用npm
的模块能力。
Deno
自带可以通过URL
来import
一个JavaScript
或TypeScript
模块文件,符合ES6
模块标准jspm
是基于SystemJS
的能力,以npm
或GitHub
为注册表,去将其JavaScript
模块封装成浏览器可以直接调用ES6
模块Deno
可以借助jspm.io
这个jspm
直接调用在npm
上有注册的JavaScript
模块包- 但是
Deno
调用的npm
模块,必须是纯JavaScript
或者browser
能力的(例如: react、react-dom、lodash 之类),暂时兼容不了带Node.js
API的模块。
如果通过jspm.io
引入 npm
的 lodash
模块,使用方式如下:
import lodash from "https://dev.jspm.io/lodash";
const array = [1];
const result = lodash.concat(array, 2, [3], [[4]]);
console.log(result);
// export: [1, 2, 3, [4]]
源码地址 https://github.com/chenshenhai/deno_note/blob/master/demo/npm/react.tsx
/// <reference path="https://deno.land/x/types/react/v16.13.1/react.d.ts" />
import React from "https://dev.jspm.io/react";
import ReactDOMServer from "https://dev.jspm.io/react-dom/server";
const Module = (data: string) => {
return (
<div className="mod">
<div>data: {data}</div>
</div>
)
}
const View = () => {
return (
<div className="hello">
{Module('hello world')}
</div>
)
}
const html = ReactDOMServer.renderToString(View())
console.log(html)
- 执行代码
deno run react.tsx
- 结果会输出
<div class="hello" data-reactroot=""><div class="mod"><div>data: <!-- -->hello world</div></div></div>
源码地址 https://github.com/chenshenhai/deno_note/blob/master/demo/npm/lodash.ts
import lodash from "https://dev.jspm.io/lodash";
const array = [1];
const result = lodash.concat(array, 2, [3], [[4]]);
console.log(result);
- 执行代码
deno run lodash.ts
- 结果会输出
[1, 2, 3, [4]]
源码地址 https://github.com/chenshenhai/deno_note/blob/master/demo/npm/koa_compose.ts
import compose from "https://dev.jspm.io/koa-compose";
let middleware = [];
let context = {
data: []
};
middleware.push(async(ctx: any, next: Function) => {
console.log('action 001');
ctx.data.push(2);
await next();
console.log('action 006');
ctx.data.push(5);
});
middleware.push(async(ctx: any, next: Function) => {
console.log('action 002');
ctx.data.push(2);
await next();
console.log('action 005');
ctx.data.push(5);
});
middleware.push(async(ctx: any, next: Function) => {
console.log('action 003');
ctx.data.push(2);
await next();
console.log('action 004');
ctx.data.push(5);
});
const fn = compose(middleware);
fn(context)
.then(() => {
console.log('end');
console.log('context = ', context);
});
- 执行代码
deno run koa_compose.ts
- 结果会输出
action 001
action 002
action 003
action 004
action 005
action 006
end
context = { data: [ 2, 2, 2, 5, 5, 5 ] }