spatialillusions / milsymbol

Military Symbols in JavaScript
www.spatialillusions.com/milsymbol
MIT License
556 stars 136 forks source link

Proper way of importing as esm #289

Closed HermanBilous closed 7 months ago

HermanBilous commented 1 year ago

Hi! Thanks for the package. It's awesome!

I've been trying to import the package as an es module in my react app, but failed. Basically, what I was expecting to do:

  1. run pnpm i milsymbol
  2. add following code:
    
    import { ms, std2525d } from 'milsymbol';

ms.addIcons(std2525d);


3. use ms as usual.

With current package setup it's impossible, since the package only exports /index.js and not /index.esm.js. This is fine, and using `import ms from 'milsymbol'` works, but if I only import what I need, I will get ~120 kb reduction in size.  
In order to achieve this, I created a fork and made a few changes, published to npm. So now I import from my own package.

I'd like to use this lib in the future, and I think that one of the ways to handle this, without making breaking changes is to introduce a separate export like 'milsymbol/es' that will contain index.esm.js as well as proper types. I could create a PR for that, but I'd still need help to create .d.ts files for it (specifically around what type `std2525d` is). Would you be open to such changes, and will you be able to provide help with typings?

Cheers!
ben-xD commented 7 months ago

I'm not sure if this was fixed, but it seems doable:

Quick example:

import ms from 'milsymbol';
const symbol = new ms.Symbol("sfgpewrh--mt");
const canvasElement = symbol.asCanvas(1)
const symbolElement = symbol.asDOM();

export const IconsTest = () => {
  const containerRef = useRef<HTMLDivElement>(null);
  // const svgRef = useRef<SVGElement>(null);
  useEffect(() => {
    // svgRef.current!.innerHTML = symbolElement.innerHTML;
    containerRef.current!.appendChild(canvasElement);
    containerRef.current!.appendChild(symbolElement);
  }, []);
  return (
    <div ref={containerRef}/>
  );
}
HermanBilous commented 7 months ago

Hey @ben-xD, thanks. Perhaps I should have phrased my issue title better: there is no way to import milsymbol from index.esm.js. Like I wrote in the original post, import ms from 'milsymbol'; works, but I want to import from index.esm.js. This way, the import will be tree-shakeable. I have a fork of this package where I utilized it to a certain extent.

spatialillusions commented 7 months ago

Since I’m a bit unsure about what changes that needs to be done to get this working in the correct way, I would love to get a pull with the changes that needs to be done.

Last time I tried to update package.json to fix this it ended up breaking the import in angular if I recall correctly.