Last active
July 13, 2020 11:39
-
-
Save hyrious/97be9d5d7bf7448df951ff328d43e1dd to your computer and use it in GitHub Desktop.
不支持内部继续 require
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"axios": "https://cdn.jsdelivr.net/npm/axios/dist/axios.js", | |
"node-fetch": "https://cdn.jsdelivr.net/npm/node-fetch/lib/index.js", | |
"markdown-it": "https://cdn.jsdelivr.net/npm/markdown-it/dist/markdown-it.js", | |
"remarkable": "https://cdn.jsdelivr.net/npm/remarkable/dist/remarkable.js" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// see npm: require-from-url | |
// compile('module.exports = 42', '.') => 42 | |
const path = require('path'); | |
function compile(code, filename) { | |
const Module = module.constructor; | |
const m = new Module(filename, module.parent); | |
m.filename = filename; | |
m.paths = Module._nodeModulePaths(path.dirname(filename)); | |
m._compile(code, filename); | |
return m.exports; | |
} | |
const https = require('https'); | |
function gets(url) { | |
return new Promise((resolve, reject) => { | |
// prettier-ignore | |
https.get(url, res => { | |
const buf = []; | |
res.on('data', data => { | |
buf.push(data); | |
}).on('end', () => { | |
resolve(Buffer.concat(buf).toString()); | |
}); | |
}).on('error', reject); | |
}); | |
} | |
const importmap = require('./importmap.json'); | |
async function requireFromUrl(url) { | |
if (url in importmap) url = importmap[url]; | |
const code = await gets(url); | |
return compile(code, url); | |
} | |
async function testAxios() { | |
const axios = await requireFromUrl('axios'); | |
console.log(axios); | |
} | |
async function testNodeFetch() { | |
const fetch = await requireFromUrl('node-fetch'); | |
console.log(fetch); | |
} | |
async function testMarkdownIt() { | |
const MarkdownIt = await requireFromUrl('markdown-it'); | |
console.log(MarkdownIt); | |
} | |
async function testRemarkable() { | |
const { Remarkable } = await requireFromUrl('remarkable'); | |
console.log(Remarkable); | |
} | |
async function runTests() { | |
await Promise.all([ | |
testAxios(), | |
testNodeFetch(), | |
testMarkdownIt(), | |
testRemarkable(), | |
]); | |
} | |
async function main() { | |
try { | |
await runTests(); | |
} catch (e) { | |
console.log(e.message); | |
} | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment