Last active
November 3, 2020 23:32
-
-
Save hyrious/150ce61bb468d74a27f7e61eb788dcbc to your computer and use it in GitHub Desktop.
export the right thing
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
const fetch = require('node-fetch') | |
const importMap = { | |
react: "react/umd/react.production.min.js", | |
'react-dom': "react-dom/umd/react-dom.production.min.js", | |
} | |
const imported = {} | |
function nullish(a, b) { | |
return a == null ? b : a // nodejs 14 can do a ?? b | |
} | |
function fakeRequire(path) { | |
return nullish(imported[path], {}) | |
} | |
async function listExports(lib, deps = {}) { | |
const path = nullish(importMap[lib], lib) | |
const url = 'https://cdn.jsdelivr.net/npm/' + path | |
const raw = await fetch(url).then(r => r.text()) | |
const code = 'var exports={},module={exports};' + raw + 'return exports' | |
const result = imported[lib] = Function('require', code)(fakeRequire) | |
return Object.keys(result).filter(e => !e.startsWith('_')) | |
} | |
;(async function() { | |
const memo = {} | |
const work = async a => memo[a] = await listExports(a) | |
await work('react') | |
await work('react-dom') | |
function helper(a, b) { | |
const snippet = '{ ' + memo[a].join(', ') + ' }' | |
console.log('const ' + snippet + ' = ' + b + ';') | |
console.log('export ' + snippet + ';') | |
console.log('export default ' + b + ';') | |
} | |
helper('react', 'React') | |
// helper('react-dom', 'ReactDOM') | |
})() | |
// outputs: (react 17.0.1) | |
/* | |
const { Fragment, StrictMode, Profiler, Suspense, Children, Component, PureComponent, cloneElement, createContext, createElement, createFactory, createRef, forwardRef, isValidElement, lazy, memo, useCallback, useContext, useDebugValue, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useReducer, useRef, useState, version } = React; | |
export { Fragment, StrictMode, Profiler, Suspense, Children, Component, PureComponent, cloneElement, createContext, createElement, createFactory, createRef, forwardRef, isValidElement, lazy, memo, useCallback, useContext, useDebugValue, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useReducer, useRef, useState, version }; | |
export default React; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment