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

How to refresh a specific component or page in Angular without causing the entire page to reload

Is there a way to make the selected file visible without having to reload the entire page? I want to find a cleaner method for displaying the uploaded document. public onFileSelected(event): void { console.log(this.fileId) const file = event.targe ...

Placing a v-model within a Vue.js component

I am attempting to achieve something similar to this specific scenario, but I am struggling to find the appropriate technical terminology to describe it. Unfortunately, I haven't been able to locate a solution for this issue. <div id="app"> ...

Encountering login issues with npm due to the presence of the .npmrc file in the project root

I encountered an issue with my .npmrc file located in the project root directory. When I attempted to run npm login, it resulted in an error message. npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY npm ERR! errno UNABLE_TO_GET_ISSUER_CERT_LOCALLY Interes ...

Exploring the integration of Ant Design Vue within HTML code

How can ant design vue be implemented in HTML? I attempted to install this library using npm and obtained the following files: antd.js, antd-with-locales.js.map, antd.js.map, antd-with-locales.min.js, antd.min.js, antd-with-locales.min.js.LICENSE.txt, ant ...

Experimenting with Hubot in an Ubuntu environment on my local machine

Hello amazing Stackoverflow community, I'm currently in the process of creating a script for hubot. But before I dive into coding, I want to test some hubot commands in the command line (I previously did this on Windows but now need to switch to Ubun ...

How can I send back multiple error messages from a pug template in a node.js application with Express?

I am currently working on validating inputs from a form on a Node.js web server using Pug.js and Express.js. The issue I am facing is that when there are multiple problems with the user's input, only the first error is displayed to the user. How can I ...

Running Node.js code from npm within Swift can be achieved by following these steps:

I am looking to integrate a Node JS package downloaded from npm into my Cocoa App and run it using Swift. Despite searching online, I have not been able to find any information on whether it is possible to call an npm package from Swift. Can anyone help m ...

Updating the DOM does not occur by simply adding an object to the Array; instead, the database is updated once the data has

My database has verified data that is being updated, however, the DOM is not reflecting these updates. <ul> <li ng-repeat="aReview in reviewList"> .... .... </li> </ul> <script> if(globalMethods.stringVa ...

Parent scope receives directive updates with a slight delay

I recently made a transition of my simple paging feature from the controller to a directive, but encountered a peculiar issue. Whenever I update the parent scope from within the directive, the changes only reflect on the next alteration. For instance, if t ...

Vuex has reserved this keyword

I am working on a Laravel application with the following code in app.js: require('./bootstrap'); window.Vue = require('vue'); import { store } from './store/store' import Sidebar from './Sidebar' Vue.component(& ...

Enhance with Laravel combined with AngularJS

I've encountered some issues with the "edit" part while working on a Laravel + AngularJS CRUD application. An internal server error is being displayed, and I'm seeking assistance to understand its cause. Error "GET localhost/crudtcc/public/ap ...

Having trouble populating the input text field with the selected value from a dropdown using JavaScript

I have implemented a JavaScript function to retrieve the id of a dropdown select with id='odrid'. The script looks like this: $('#odrid').change(function(){ $.getJSON( 'fetch.php', 'odrid='+$(&ap ...

Angular: Utilizing Nested ng-repeat Alongside groupBy Feature on Initial Page Load or Refresh

With some help, I've made it this far on my project. However, I need to take one more step to achieve my goal. I want to group data based on an attribute that is currently passed through an ng-click action. Is there a way to automatically do this on p ...

Executing a C# program that sends a web request without using JavaScript

My goal is to programmatically download the contents of a website, but it seems like this content is being loaded through ajax calls. Interestingly, when I disable javascript in my browser, only one request is made by the page and all the content is displa ...

How to Retrieve the Number of Requests in an Express Application

Is there a method to retrieve the overall count of requests in a specific route using Expressjs? ...

Is there a way to display the output of jQuery in an input box rather than a span?

I need to display the result of this function in an input box instead of a span tag because I plan to utilize the result in the following form. function checkChange(){ $.ajax({ url: "ordercalculate.php", data: $('form').seria ...

Ensuring consistency of Angular route data and maintaining data synchronization

In my Angular application, I have a table that displays a set of items and allows inline editing directly within the table. The data is fetched from an HTTP API through a service, which retrieves the data and injects it into the application. The issue ari ...

Carry out numerous commitments across a range of elements

I have a list of objectIds and I want to perform operations on different collections based on each Id. I prefer executing the operations sequentially. var removeOperation = function(objectified){ return Comps.findOne({reviews : objectified}).populate([ ...

What is the best approach for creating a brute-force solution for finding the smallest change algorithm

Looking for a solution to this algorithm challenge: Create a function that can determine the minimum amount of change that cannot be made with the given coins. function nonConstructibleChange(coins) { coins = coins.sort((a, b) => a - b); // O(nlogn) ...

"Integration of the 'node_modules' directory within a module prior to publication on the NPM

After releasing my module to the NPM registry, I proceeded to install it using npm install --save-dev X To my surprise, upon checking project Y which relies on X, I noticed that the node_modules folder was duplicated, resulting in this structure: Y/node ...