X Tutup
Skip to content

[Bug] Cannot import two.js in typescript project #531

@nmay231

Description

@nmay231

Describe the bug
I guess this is a continuation of #526. The generated types in two.js@0.7.5 don't work right off the bat. At least not with the default create-react-app typescript setup.

To Reproduce
Steps to reproduce the behavior:

  1. npx create-react-app twojs-demo --template typescript
  2. cd twojs-demo
  3. npm i two.js@0.7.5
  4. Replace src/App.tsx with the following:
import { useEffect } from 'react';
import Two from 'two.js'

function App() {
  useEffect(() => {
    const two = new Two({
      fullscreen: true,
      autostart: true,
    })

    const container = document.getElementById('container');
    if (container) two.appendTo(container)

    var rect = two.makeRectangle((two as any).width / 2, (two as any).height / 2, 50 ,50);
      (two as any).bind('update', function() {
        rect.rotation += 0.001;
      });
  }, [])

  return (
    <div id='container' />
  );
}

export default App;
  1. Observe the error: File 'twojs-demo/node_modules/two.js/types.d.ts' is not a module.

Potential fix
Modify node_modules/two.js/types.d.ts with the following changes:

- declare namespace Two {
+ declare module 'two.js' {
+   export default Two;

...

Reload the dev server or resave App.tsx to enact HMR. The code should run with no problems.

Notes

Besides not being able to import two.js, the type definitions were lacking the .width, .height, and .bind attributes of a new Two() instance. That's why the App.tsx casted (two as any). There might be other small problems like that.

I never used the jsdoc typescript generator, but perhaps there is a way to switch to declare module instead of declare namespace? I think 'module' is more modern in typescript (I would have to double-check).

Additionally, there should be a new version of @types/two.js to mention that that package is just a stub file since you are including types here. I can open a PR over there if you are ready to take that step.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      X Tutup