43081j / id3

A JavaScript ID3 tags parser for Node & browsers.
MIT License
335 stars 63 forks source link

Usage in a web browser with a bundler #60

Open catamphetamine opened 1 year ago

catamphetamine commented 1 year ago

Hi. The readme provides an example of using this library in a web browser via a <script/> tag:

<input type="file">

<script type="module">
import * as id3 from '//unpkg.com/id3js@^2/lib/id3.js';

document
  .querySelector('input[type="file"]')
  .addEventListener('change', async (e) => {
    const tags = await id3.fromFile(e.currentTarget.files[0]);
    // tags now contains v1, v2 and merged tags
  });
</script>

That's not the most conventional way of using packages in a web browser. The most conventional one is using a "bundler" like Webpack and importing directly from npm packages.

Example:

import { fromFile } from 'id3js'

const tags = await fromFile(file)
// tags now contains v1, v2 and merged tags

But it throws an error:

Module not found: Can't resolve 'fs' in '...\node_modules\id3js\lib'
node_modules/id3js/lib/localReader.js

So the main file of the library looks like this: https://unpkg.com/browse/id3js@2.1.1/lib/id3.js

{
  "name": "id3js",
  "version": "2.1.1",
  "main": "./lib/id3.js",
  "types": "./lib/id3.d.ts",
  "type": "module",
  ...
}
...

export async function fromPath(path) {
  const mod = await import('./localReader.js');
  return fromReader(new mod.LocalReader(path));
}

...

For some reason, it seems to execute that await import() statement even though I didn't call that specific function called fromPath(). The error happens before calling any function, already at the import level:

import * as Id3 from 'id3js'

I've fixed that in my fork by introducing two separate exports: /browser and /node.

See the updated README: https://github.com/catamphetamine/id3

It now works in my setup (Webpack).

I've also added a function for getting an album cover image data URL.