skip to Main Content

I have an npm module installed and can’t figure it out how to use it in the browser after importing it.

First I installed the npm module by (just an example dummy module):

npm install sample-module

In my package.json I have added then:

"type": "module"

My server.js on Node looks like this:

import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';

const PORT = process.env.PORT || 8080;
const app = express();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

app.use('/assets', express.static('assets'));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname) + '/views/index.html');
});

app.listen(PORT, _ => {
    console.log(`App deployed at Port ${PORT}`);
});

In my index.html (from /views/) I am referencing to this JS file, which is used in the browser:

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

And this script.js uses following:

import {one, two} from 'sample-module'

When I load the page in the browser I am then getting:

Uncaught TypeError: Failed to resolve module specifier "sample-module". Relative references must start with either "/", "./", or "../".

Trying to update the import statement to ./sample-module or even ../node_modules/sample-module does not work.

So my question is: How to load a module installed by npm and loaded by the import statement on the browser?

What I have tried is to remove the "type": "module" from package.json and then update all import-statements to use require() and then used browserify to generate a bundle.js file, which I again referenced then in my index.html. That worked! But using the same setup with the import-statement doesn’t worked. So how to achieve the same result with the import-statement?

Any help is appreciated.

2

Answers


  1. Chosen as BEST ANSWER

    After trying different approaches I came to an solution I want to share.

    From the script.js file I used in the browser I moved following line in server.js in Node:

    import {one, two} from 'sample-module'

    In my script.js, which is used in the browser I am then calling corresponding imported functions. Then I used browserify to build a bundle.js with command:

    browserify script.js -o bundle.js

    In the index.html I then referenced to the new bundle.js file. That way I was able to use the npm module which was imported by the import-statement in the browser.


  2. i am new at nodjs but if you try to create server using node.js i think

    npm init --y will help to simply generate an empty npm project and that will help you to avoid a lot of errors

    then make sure that package name is correct

    and try to use require rather than import

    e.x

    let express = require('express');
    let {one , two} = require('sample-module');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search