Search code examples
javascriptnode.jsgulp

How to import JS library from node_modules


Can you please explain the ideology of using import/require libraries from node_modules folder.

I just want to use konva.js in my simple project, using node.js as a back end with live-server extension configured.

If I import it right into HTML file like this

<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<script> /*using konva library here or *.js*/</script>

Everything works
As I understood, this URL imports whole konva.min.js right into my HTML file

If I copy konva.js file from /node_modules package into my /src folder

And use code like this in my HTML

    <script src="konva.min.js"></script>
    <script src="script.js"></script>

I have access to konva library in script.js

In server-side scripts, invoked by node.js I used statement like this to access packages in node_modules

var liveserver = require("live-server");

P.S. Why doesn't import work here? Node.js doesn't have import instructions?

But the main question is how to use the same syntax of require()/ import on client-side scripts and not to use <script> tags to import libraries?

 import konva from 'konva';
 /* js code next*/ 

OR

 var konva = require('konva');
 /* js code next*/

I need to use task managers? What should I do? Search for dependencies in each .js file and use tasks to import these dependencies right into project folder? But, for example, for gulp I found different libraries to format code, but can't find needed one to import dependencies


Solution

  • Node.js is a server-side runtime environment, what you need is to use the node_modules libraries on the client/browser side.

    Using browserify

    browserify will recursively analyze all the require() calls in your app in order to build a bundle you can serve up to the browser in a single script tag.

    It will bundle you require and import into a single js file for use in a script tag.

    Using import on client side

    <script type="module">
      import {addTextToBody} from './utils.mjs';
    
      addTextToBody('Modules are pretty cool.');
    </script>
    

    All you need is type=module on the script element, and the browser will treat the inline or external script as an ECMAScript module

    // utils.mjs
    export function addTextToBody(text) {
      const div = document.createElement('div');
      div.textContent = text;
      document.body.appendChild(div);
    }
    

    These are some great articles to get a better understanding of this :