Skip to content

jojobyte/browser-import-rabbit-hole

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Browser import Rabbit Hole

Deducing a way to use IIFE modules that do not provide export default or export let rabbit = 'hole' in browser and preserving JSDoc type hinting.

TL;DR

Wrap it

// sadness.js
// the IIFE module you want to wrap

/**
 * @typedef Foo2
 * @prop {Greet2} greet
 * @prop {Uint8Array} secret
 */

/**
 * @callback Greet2
 * @param {String} name
 */

/** @type {Foo2} */
var Foo2 = ("object" === typeof module && exports) || {};

(function (window, Foo2) {
  "use strict";

  let Crypto = window.crypto || require("node:crypto");

  Foo2.secret = new Uint8Array(16);
  Crypto.getRandomValues(Foo2.secret);

  Foo2.greet = function (name) {
    console.log(`Hello, ${name}!`);
  };

  window.Foo2 = Foo2;
})(/** @type {Window} */ (globalThis.window || {}), Foo2);

if ("object" === typeof module) {
  module.exports = Foo2;
}
// madness.js
// Wrapper module
import './sadness.js'
import * as Types from './sadness.js'

/** @type {Types} */
let Sadness = window.Foo2

export default Sadness
<!-- index.html -->
<script type="module">
/**
 * now this works in modern browsers
 * with no transpilation and gives
 * JSDoc type hinting
 */
import madness from './madness.js';

console.log(
  'browser',
  madness,
  madness.secret.toString()
)

madness.greet('madman')
</script>

About

Deducing a way to use IIFE modules in browser and preserving JSDoc type hinting.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published