Search code examples
javascriptnpmnpm-installyarnpkg

Why I need to use a relative path to an installed library?


Context : I'm trying to use Editor.js library for a personal project

Editor.js documentation

There is the project directory :

enter image description here

There is the package.json :

{
  "name": "quicknoteapp",
  "version": "1.0.0",
  "description": "",
  "main": "myApp.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "electron ."
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@editorjs/editorjs": "^2.19.0",
    "electron": "^10.1.5",
    "menubar": "^9.0.1"
  }
}

My index.html :

<script type="module" src="main.js"></script>

And I import my library from main.js :

import EditorJS from '@editorjs/editorjs';

Finally, the console come up with this error :

TypeError: Module specifier, '@editorjs/editorjs' does not start with "/", "./", or "../". Referenced from file:///Users/charles/Desktop/QuickNoteApp/main.js

Ok, I need to add the relative path when I import the module. But I don't like to do it. Why I need to use a relative path to an installed library ?

Why I can't do the same as the documentation? What I'm doing wrong during the project set up ? I don't think this is normal to add the path to each script. If not, why using npm... and got a node_module folder.


Solution

  • NPM is designed to manage packages for Node.js not for web browsers.

    Web browsers are not Node.js. They do not support Node.js' module path resolution features (which involve searching multiple directories for matching files: Web browsers do not have access to directory listings, only to URLs).

    The instructions assume you are using a tool like Webpack which uses Node.js to bundle JS modules into a single file for delivery to a browser. They don't assume you are going to load the modules into the browser directly.