Skip to content

Instantly share code, notes, and snippets.

@libetl
Created August 31, 2023 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save libetl/e713b339ba3c10d424c658b27fca677f to your computer and use it in GitHub Desktop.
Save libetl/e713b339ba3c10d424c658b27fca677f to your computer and use it in GitHub Desktop.
loadDependenciesFromWindow.js
const path = await import('node:path')
const loadDependenciesFromWindow = (mapping) => (
{
name: "load-dependencies-from-window",
setup(build) {
build.onResolve({ filter: /.*/ }, (args) => {
const condition = args.kind === 'import-statement'
&& !args.path.startsWith('.') && !args.path.startsWith('/')
const result = ({
path: condition ? args.path :
args.kind === 'import-statement' || args.kind === 'entry-point' ?
path.resolve(args.resolveDir, args.path.replace(/\.js(x)?$/, '.ts$1')) : args.path,
namespace: condition ? 'load-dependencies-from-window' : undefined
})
return result;
});
build.onLoad({ filter: /.*/, namespace: 'load-dependencies-from-window' },
(args) => {
return ({ contents: `module.exports = window.${mapping[args.path]}` })
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment