Getting your JS project off the ground with NPM!

I am looking to develop a vanilla JavaScript project that utilizes npm packages, but I want to do it without using bundlers like Webpack.

Here is a basic structure:

index.html:

<div id="app"></div>
<script src="./index.js" type="module"></script>

index.js:

import { sandbox } from "./sandbox.js";

const appDiv = document.getElementById('app');
appDiv.innerHTML = `<h1>JS Starter</h1>`;
sandbox.run();

sandbox.js:

import { from } from "rxjs";
import { map, filter, reduce } from "rxjs/operators";

export const sandbox = {
    run() {
        console.clear();
        var source = ['1', '1', 'foo', '2', '3', '5', 'bar', '8', '13'];

        from(source).pipe(
            map(num => parseInt(num)),
            filter(num => !isNaN(num)),
            reduce((acc, val) => acc + val)
        ).subscribe(num => console.log(num));
    }
}

package.json:

{
  "name": "jsblank",
  "version": "1.0.0",
  "private": true,
  "dependencies": {
    "rxjs": "^6.5.3"
  }
}

Challenges Encountered:

1. Opening index.html directly results in a CORS exception due to file not running on the server:

Access to script at 'file:///C:/Projects/jsBlank/index.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

2. Removing "type="module"" from index.html leads to an error:

Uncaught SyntaxError: Cannot use import statement outside a module

3. Attempting to launch a static local server:

npm i -g http-server
http-server

The server has access to all files except for dependencies from node_modules.

Current Question: How can I create a vanilla JavaScript project with npm dependencies and successfully run it without using Webpack or any other bundler?

Webpack can be used if necessary, but I prefer avoiding it for this small test project.

P.S. StackBlitz provides a similar starter template: https://stackblitz.com/edit/js-zt2q49 But how can I set up and run it locally?

Answer №1

Access to all files is granted, excluding dependencies located in the node_modules directory.

You have full access to them, but it is crucial to provide the complete path to the module (which includes referencing the node_modules directory).

It is important to note that web browsers do not function like Node.js and cannot search within the node_modules directory for modules. You must specify the precise URL to the JS file.

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

HighCharts: visualize vertical stacked bars displaying the distribution of percentages within each stack

I currently have a stacked bar chart similar to the one shown in this JSFiddle demo. My goal is to transform the stacks so that each bar represents a percentage of the total stack height. For instance, in the Apples stack we currently have values {3, 2, 5 ...

Tips for effectively highlighting search text within HTML content without causing any issues

I am in search of a solution that can assist me in searching for specific terms within an HTML string while also highlighting them. I have the ability to remove the HTML content from the string, but this poses the problem of losing the context of the origi ...

How to initiate a refresh in a React.js component?

I created a basic todo app using React, TypeScript, and Node. Below is the main component: import * as React from "react" import {forwardRef, useCallback, useEffect} from "react" import {ITodo} from "../types/type.todo" import ...

Error: The meteor package encountered a SyntaxError due to an unexpected reserved word 'export'

I've made some modifications to a meteor package by adding this line: export const myName = 'my-package' However, I'm encountering an error: export const myName = 'my-package' ^^^^^^ SyntaxError: Unexpected reserved word I ...

Conflicting submissions

Can anyone help me with a JavaScript issue I'm facing? On a "submit" event, my code triggers an AJAX call that runs a Python script. The problem is, if one submit event is already in progress and someone else clicks the submit button, I need the AJAX ...

numerous sections within a solitary webpage

I need to implement multiple tabs on a single page, how do I modify the code to make this possible? Take a look at the codepen for reference. Here is the jquery code I have written so far: var tabs = $(".tabContainer ul li a"); $(".tabConten ...

Issue with jQuery.off when using a dynamic function name

I am currently implementing a modular pattern for writing my JavaScript code and it has been an enjoyable experience! However, I have encountered a challenging situation. My Namespace structure looks like this: var settings, handlers, objects, Namespace ...

Direct the /username path to /[user]/[tab].js instead of [user]/index.js in Next.js

My goal is to develop a user profile page that displays content based on the current tab the user is viewing. The tab is determined by what is provided in the URL (e.g. /username/tab1). The challenge I am facing is that one of the tabs the user can access ...

Exploring the differences between detecting the XMLHttpRequest object in JavaScript and using the try

When it comes to determining browser support for AJAX, I typically rely on object detection like this: if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } ...

The AngularJS ng-repeat filter {visible: true} does not respond to changes in properties

var myApp = angular.module('myApp', ['infinite-scroll']); myApp.controller('DemoController', function($scope, $timeout, $rootElement) { $scope.$rootElement = $rootElement; $scope.$timeout= $timeout; $scope.init = ...

What are the steps to effectively implement the useEffect hook in React?

I'm facing an issue where I am trying to return a function that utilizes useEffect from a custom usehook, but I keep getting the error "useEffect is called in a function which is neither a react function component nor a custom hook." Here's what ...

Error: Unable to access the 'number' property of an undefined value

How can I use Axios to delete a book from my list? I've tried using the URL of my database along with the id, but it seems like the id is not specified in the URL and remains undefined. This is what my code looks like: export default class ListBooks ...

The onchange function seems to be malfunctioning when attempted with AJAX

Help needed: I'm new to AJAX and facing an issue. I have implemented AJAX pagination to display data, which is working fine. But now I want to add a filter to the displayed data, however, the filter is not functioning correctly. <select name="prof ...

JavaScript can be used to deactivate the onclick attribute

Is there a way to deactivate one onclick event once the other has been activated? Both divs are initially hidden in the CSS. I'm new to programming, so any help is appreciated. Markup <a id="leftbutton" href="#" onclick="showDiv(this.id); return ...

Determining the emptiness of an array in Postman using node.js

When I receive a response, it is in the following format: { "test1": [], "test2": [], "test3": [], "test4": null, "test5": [] } This is the response that I get after making a request. I need to verify whether test1 is empty or not. ...

JQuery click event does not play nicely with Javascript array splice functionality

When using for loops, I noticed that array.splice doesn't seem to be working as expected. The array remains unchanged. I tried moving things around and found that it still doesn't work in Chrome. var menu =['#men','#wmen',&a ...

Is there a need for the package-lock.json file if the package.json file already lists specific versions?

Dealing with the duality of npm's package.json and package-lock.json can be quite challenging. I have a question that might shed some light on their relationship: If we create a package.json file that only includes exact versions for all dependencies ...

When applying a cell formatter to change the color of a Tabulator cell, the text displayed is being

I am attempting to dynamically change the color of a tabulator cell based on its input. My initial approach was to simply try changing the cell's color. After running the following code, here is what I observed: function testFormatter(cell, formatt ...

Encountering difficulties loading compiled assets (CSS) following the implementation of Varnish and Hitch

After installing Varnish version 7.0.2 and hitch 1.7.0 on my Ubuntu 20.04 server, I encountered an issue where CSS is not loading. Interestingly, when I stop Varnish, the CSS loads perfectly fine. I attempted to bypass the site using the following code s ...

Clear the Material-UI textfield upon form submission

After submitting the form, how can I clear the value from the TextField? All of the components in my code are functional components, not class ones. The example below shows one of the TextFields, with others similar to it. Currently, setting type='sea ...