Can't understand importing node modules

Viewed 140

I'm very new to web development. I'll try to make the question short. Im trying to use a javascript library called euclid.ts. Its page tells you this:

Instructions to import euclid.ts

So this i what i did:

First I ran the command. Then in my html file, called index.html I import a script file called sketch.js

<body>
<script type="module" src="sketch.js"></script>
</body>

Then in my sketch.js file i have this line right at the top:

import {Point, Line} from '@mathigon/euclid'

The problem is, when I open index.html in the browser I get this error:

Uncaught TypeError: Error solving the module “@flatten-js/core”. 
Mode specifiers must start with “./”, “../” or “/”.

I can't understand what I'm doing wrong (and how is the browser supposed to know which file to import if I don't even specify the file in the import line)

2 Answers

You need some way of resolving the packages before they go into browser. Browser doesn't not know how to resolve the dependencies for the package '@mathigon/euclid'. Code editors on the other hand can resolve the dependencies. The error that you see would be an error for a package that '@mathigon/euclid' depends upon.

So the actual sketch.js which runs in the browser should be packaged and should be the file with code from '@mathigon/euclid' and all it's dependencies.

You can look at webpack-cli for an easy way to generate the bundled sketch.js https://www.npmjs.com/package/webpack-cli

After installing cli i believe you could do webpack-cli build --entry sketch.js (Not tested)

One option for compiling/bundling is via "webpack". https://webpack.js.org/guides/getting-started/

If you setup a folder like so:

/project
  package.json
  sketch.js

package.json

{
  "dependencies": {
    "@mathigon/euclid": "^0.6.9",
    "webpack": "^5.20.1",
    "webpack-cli": "^4.5.0"
  }
}

sketch.js

import { Point, Line } from '@mathigon/euclid'


console.log ("sketch")

and then run either npm install or yarn install

and then run ./node_modules/.bin/webpack ./sketch.js

you can generate a bundle that includes @mathingo/euclid at dist/sketch.js

Afterwards, the script tag could look like:

<script src="dist/sketch.js"></script>
Related