magenta / magenta-js

Magenta.js: Music and Art Generation with Machine Learning in the browser
https://magenta.tensorflow.org
Apache License 2.0
1.96k stars 311 forks source link

How to correctly import with webpack & ES5 support #432

Open cifkao opened 4 years ago

cifkao commented 4 years ago

I have a browser project which uses npm, webpack and babel for ES5 compatibility. I'm using some functions from @magenta/music (core and protobuf), but I'm still confused about how to import it correctly.

All of the following work in Chrome on my desktop:

// 1)
import * as mm from '@magenta/music';

// 2)
import * as mm from '@magenta/music/es6';

// and even 3)
import * as mm from '@magenta/music/node';

but the following fails:

// 4)
import * as mm from '@magenta/music/es5';

with Module not found: Error: Can't resolve '@magenta/music/es5' (indeed, there are no .js files in the es5 directory).

Are 1) and 2) equivalent? Then I suppose neither provides ES5 compatibility? How do I make 4) work? It would be great if this could be clarified in the readme.

notwaldorf commented 4 years ago

The es5 build doesn't work in a module-y way (because modules are not es5). You have to use the es6 builds for that. iirc: 1) is the es5 build 2) es6 build 3) node build (that uses require)

Here's a sample repo I made to show it working with TS and webpack: https://github.com/notwaldorf/example-magenta-in-ts

cifkao commented 4 years ago

I see, thanks! So you're importing '@magenta/music/es6' but your tsconfig says "target": "es5" so it will get compiled to ES5, is that correct? But if I'm importing from "plain" JS (not TS, just webpack), I think it will just pack the ES6 code.

notwaldorf commented 4 years ago

Yup, the tsconfig target is what my project outputs (so I can use es6 sources, but the thing I'm outputting will be es5, and all the new JS features will be prayed away by that webpack config). Yeah, using JS should be similar to this, modulo a webpack flag somewhere (telling it to use babel or something). Unfortunately JS infra is not my forte, but that should be a fairly common and googleable non-magenta problem. :)