jonobr1 / two.js

A renderer agnostic two-dimensional drawing api for the web.
https://two.js.org
MIT License
8.29k stars 454 forks source link

[Bug] Type Error when using vector from two.module.js #654

Closed eulertour closed 2 years ago

eulertour commented 2 years ago

Describe the bug Using Two.Vector after importing two.module.js results in a type error, despite working properly in the browser.

To Reproduce

import Two from '../src/lib/two.module.js

new Two.Vector();

Expected behavior No type error when using the Vector class.

Screenshots Screen Shot 2022-08-14 at 3 04 02 AM

Environment (please select one):

Desktop (please complete the following information):

eulertour commented 2 years ago

FWIW, I managed to get around the error by building the Two and Vector modules manually and importing them separately:

  // utils/build.js

  esbuild.buildSync({
    entryPoints: [
      path.resolve(__dirname, '../src/two.js'),
      path.resolve(__dirname, '../src/vector.js'),
    ],
    // outfile: paths.esm,
    outdir: path.resolve(__dirname, '../build/modules'),
    bundle: true,
    target: 'es6',
    format: 'esm'
  })

However, the code is then duplicated between the two.js module (which is enormous) and the vector.js module. Is this unavoidable without tree shaking?

jonobr1 commented 2 years ago

The Two object isn't just a namespace but a class that depends on a lot of things (including Vector). So, it's not possible to tree shake. But, if you know what renderer you're using you can use that directly and it will benefit from trees shaking. Your code unfortunately needs to change a bit to conform to how the renderers work. Let me know if you'd like to see an example of this.

eulertour commented 2 years ago

Seeing an example would be a big help 👍

jonobr1 commented 2 years ago

Here's a simple example: https://codepen.io/jonobr1/pen/xxWQbJj

I'm using remote imports, but you should be able to use NPM or clone the repository and then directly access the source files for your project. Then, each module will only import what's needed and when you finally build (in what looks like esbuild for your project) the overall size of Two.js will be drastically reduced.


You'll notice though that none of the make functions, e.g: two.makeCircle exist, nor any of the conveniences like request animation frame and auto resize the canvas to be fullscreen. But, all of those things are relatively straightforward to implement yourself without any of the hassle of the entire library.

Hope this helps