Is it possible to utilize npm packages within a standard web page without any frameworks or libraries?

I am currently working on a basic website created using vanilla HTML, CSS, and JS files.

My goal is to incorporate the

import { moment } from "moment"
syntax into my JS files. However, after adding npm to my project, installing moment with npm install, and implementing that syntax, I encounter an error when running my app using live-server:

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

Answer №1

Absolutely, it is indeed possible. Browser support for native ES6 modules has been around for over 6 years now. Below is an example setup for Express, but this should be compatible with any major web server.

index.html:

<!DOCTYPE html>
<html>
<head>
  <script type="importmap">
    {
      "imports": {
        "moment": "/moment"
      }
    }
  </script>

  <script type="module" src="/app.js"></script>
</head>
<body>
  <h1>Moment</h1>
  <div></div>
</body>
</html>

app.js:

import moment from 'moment';
let x = new moment();
document.querySelector('div').textContent = x;

index.js:

import express from 'express';
const app = express();
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

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

app.get('/app.js', (req, res) => {
  res.set('Content-Type', 'application/javascript');
  res.sendFile(__dirname + '/app.js');
});

app.get('/moment', (req, res) => {
  res.set('Content-Type', 'application/javascript');
  res.sendFile(__dirname + '/node_modules/moment/dist/moment.js');
});

app.listen(8080, () => {
  console.log('Server running...');
});

package.json:

{
  "name": "example",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "express": "^4.18.2",
    "moment": "^2.29.4"
  },
  "type": "module",
  "devDependencies": {
    "@types/express": "^4.17.21"
  }
}

An import map was utilized to enable import moment from 'moment'; without using relative paths. Your web server must be configured to direct to the Moment JavaScript code.

If your web server does not support a rewrite (like I did for Moment), you will need to use the full path in the import map.

To delve deeper into native ES6 modules, check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to define a state within a map function?

This section of my code retrieves JSON data from the backend API and displays it as a list. Here is an example of my JSON data: (15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: {id: 1, t ...

Is it possible for jQuery UI Dialog to function similar to an iFrame?

Is there a way to set up my dialog box with a form so that when the form is submitted, only the dialog box changes instead of the browser location? ...

What is the function of the 'this' keyword within a Vue component?

Can someone explain how the keyword 'this' is able to access tasks that are not within the same object? anyobject = { template: '#task-list', props: { tasks: {default: []} }, data() { return { newTask: '&apos ...

PHP JSON array conversion

[ { "id":"26", "latitude":"10.308749502342007", "longitude":"123.88429984649656" }, { "id":"28", "latitude":"10.313816172726275", "longitude":"123.89030799468992" } ] I have retrieved this JS ...

Utilizing a universal JavaScript array within the jQuery document(ready) function

After using jsRender to render the following HTML template, I encountered an issue with passing data values through jQuery selectors when submitting a form via AJAX. <div class="noteActions top" style="z-index: 3;"> <span onclick="noteAction(&a ...

Issue with Material UI Tab component not appearing in the first position

I've encountered an unusual problem where the first tab is not displaying correctly. To troubleshoot, I added a second tab which appeared perfectly fine. After setting up the second tab to have the desired content of the first tab, I deleted the origi ...

An Issue with Selenium IDE Extension Utilizing JavaScript File

As a beginner in Selenium, I am currently exploring the Selenium tool: beginners guide book to learn more about it. The book explains how to utilize the Selenium IDE Extension by using a .js file to store JS functions. An example provided in the book was ...

What is the process of incorporating HTML into a jQuery program in order to immerse the world in an element?

I am looking to utilize HTML with the value in a checkbox, After adding a shortcode: <label class="HCheck">(this is val 1 )</label> and incorporating jQuery to change it to: <label class="HCheck">(this is val 1 ) ...

Pointer Permissions parsing does not permit creation

Despite meticulously following the instructions in this guide, I am encountering a 403 error when attempting to create a new row: Error code: 119 Error message: "This user does not have permission to carry out the create operation on Messages. This s ...

Display loading spinner in Material-UI Table while fetching data

Is it possible to display a Circular progress indicator while waiting for data to populate the table? How can this be accomplished? Currently, the table shows No records to display until the data is retrieved from the server. https://i.stack.imgur.com/Ljq ...

Using Javascript to populate textboxes with the value of checkboxes

Within my web application, there is a series of checkboxes that, when selected, populate a textbox located above them. If more than one checkbox is checked, their values are displayed in the textbox separated by commas. These checkboxes are structured as ...

Using Aurelia CLI: Incorporating npm package containing image assets into your Aurelia CLI application

Currently, I am attempting to incorporate lightslider (jquery slider library) from NPM into my Aurelia CLI 0.23.0 project. In order to achieve this, I have updated the dependencies in aurelia.json as follows: { "name": "lightslider", ...

What could be the reason for the inability to generate the response using response.writeHead and response.write functions?

I recently started learning about node.js and I'm facing an issue with the code inside the if and else loop for the '/socket.html' case. Despite my efforts, I always get a 200 status code and a blank response when accessing the URL localhost ...

What is the best approach to creating customizable modules in Angular2?

I'm exploring the most effective approach to configuring modules in Angular 2. In Angular 1, this was typically achieved through providers. As providers have been altered significantly, what is the preferred method for passing configuration parameters ...

Tips for creating multiple full-screen overlays in HTML

I am new to the world of web development and I am currently working on implementing a set of buttons that will trigger specific overlays when clicked. I found the following code snippet on W3schools which creates a button along with an overlay effect. < ...

Encountering an npm error while trying to deploy the latest updates to the gh-pages branch

I encountered an issue while trying to display my React page on Github pages. Despite using h-pages deploy, I keep facing an error when updating the gh-pages branch. For some reason, I can only access the *master branch. The steps I followed were : "pre ...

Using an npm package: A step-by-step guide

Recently, I added the following package to my project: https://www.npmjs.com/package/selection-popup I'm curious about how to utilize its features. Can you provide some guidance on using it? ...

How to use jQuery to dynamically add a variable to a request in Laravel 5.2

Is it feasible to append a variable to the Laravel cookie in the client using jQuery? Understandably, the Cookie is linked to the request during GET? Can you include a variable in the $request container in Laravel 5.2 using jQuery before initiating a GET ...

Submitting forms with Ajax without reloading the page can cause errors in Internet Explorer

Simply put: Upon clicking the login button in Firefox, Chrome, or Safari, the form is submitted correctly, running a validation via ajax and opening a new page. However, in Internet Explorer (version less than 9), the submission attempts to post to the c ...

Choosing Nested TypeScript Type Generics within an Array

I need help with extracting a specific subset of data from a GraphQL query response. type Maybe<T> = T | null ... export type DealFragmentFragment = { __typename: "Deal" } & Pick< Deal, "id" | "registeringStateEnum" | "status" | "offerS ...