Search code examples
javascriptnode.jstypescriptnpmweb-deployment

Can't understand importing node modules


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)


Solution

  • 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>