What is a way to import a function from a node module without the need for a Module Bundler?

I've been searching for a solution to this issue without any luck. It seems that the browser doesn't understand commonJS syntax, which is why I get a ReferenceError if I try to load require() like this

let isEven = require('is-even') // ReferenceError: Can't find variable: require
console.log(isEven(6)); // this doesn't run

So, I attempted to switch to ES6 modules as follows:

import isEven from "is-even";
console.log(isEven(6));

However, I encountered the following error in the console:

TypeError: Module specifier, 'is-even' does not start with "/", "./", or "../".

My current workaround is to use a module bundler like Webpack, which allows me to effectively use both syntaxes without any issues. But, I prefer to explore other options because debugging can be challenging with a module bundler since it's hard to pinpoint the code causing errors. Is there an alternative method to transform older JavaScript modules before serving them to the browser, aside from using a module bundler?

Answer №1

When importing in a browser, it's important to note that you cannot import from a plain filename directly. You must specify a path starting with <code>"/"
, "./", or "../", or even a full URL because browsers do not have a default location to load plain filenames from. It is crucial to be explicit about the path you provide.

Additionally, when using import in a browser, a request is made to your server and your server must be configured to serve the requested file back to the browser.

Depending on your server configuration, you may need something like this:

import isEven from "/is-even.js";
console.log(isEven(6));

Or, if scripts are handled separately by your server:

import isEven from "/scripts/is-even.js";
console.log(isEven(6));

In either case, it is up to the web server to handle these requests, locate the script file in the server's filesystem, retrieve it, and send it back to the browser.


One of the main reasons client-side code utilizes bundlers is to improve efficiency. Loading multiple script modules individually requires separate http round-trip requests to the server for each, which is not optimal. While client-side caching can help, it's still inefficient to load numerous script modules separately on the initial page load of a website. This is why bundlers exist - to collect all necessary code for a specific operation into one common script file for more efficient loading in the client-side environment.

Therefore, importing a single function like isEven() in client-side code would typically not be efficient without bundling to streamline the process.

Answer №2

give this a shot

export { isEven }; // exporting a function from the module:

this module imports a function called is-even.mjs

import { isEven } from './is-even.mjs';
console.log(is-even(6));

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

Surprising 'T_ENCAPSED_AND_WHITESPACE' error caught me off guard

Error: An error was encountered while parsing the code: syntax error, unexpected character (T_ENCAPSED_AND_WHITESPACE), expected identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\wamp\www\html\updatedtimel ...

Is there a way to use JavaScript to choose options within a <select> element without deselecting options that are disabled?

Here's the code snippet I am working with at the moment: <select id="idsite" name="sites-list" size="10" multiple style="width:100px;"> <option value="1" disabled>SITE</option> ...

Create a time of 00:19:59 using JavaScript

I am attempting to display a countdown timer that starts at 20 minutes in the format (00:20:00) using setInterval. Once the countdown is finished, it should display as (00:00:00), but I am having trouble achieving this. <body onload = "onloadFunc();" ...

Using JQuery to extract the value of cells

How to retrieve cell values using JQuery? I attempted the following code: $("#table tr").each(function(){ var result = $(this).find("td:first").html(); alert(result); }); However, instead of individual values, it returns a string comprising all ...

Enhancing the getDate function in JavaScript with additional days

My function for selecting the date is working perfectly: formatDateField(event: Date, formControl: string) { this.form .get(formControl) .patchValue( this.datePipe.transform(event.getTime(), "yyyy-MM-dd'T'HH:mm:ss&quo ...

Implement custom styles using media queries within ngView to ensure compatibility with IE browsers even after a page

Experiencing issues with CSS rules in IE10 when included in a page via ngView (using Angular 1.0.6). Works fine in other browsers (potentially IE11, not personally confirmed): Here is the CSS code: .checker { display: none; } @media (min-width: 1041 ...

The function Session.send() is dysfunctional due to the error message "session is not defined"

I am attempting to utilize session.send instead of console.log in transporter.sendMail to notify the user when the Email has been successfully sent, but I am encountering an issue. The error message "session is not defined" is appearing. Below is a s ...

Error: The variable "$this" has not been defined in the AJAX function

Recently, I've been delving into the world of javascript and ajax. I'm trying to create a dynamic select option list similar to this: https://i.sstatic.net/qELIf.png However, when attempting to compile using Google Chrome Developer tools (F12), ...

The toast added to the DOM is not displaying when using the show() function

I'm experimenting with utilizing Bootstrap 5's toast component to exhibit response messages following a jquery Ajax call. For the successful part, I conclude with this code snippet: itsToastTime(response.status, response.message) let toast = $( ...

Manipulator - Unveiling Discord User Profile Popup

Hey there, I'm currently working on a web project and I want to send messages in a Discord server using Puppeteer without relying on the Discord.js library. While I have successfully set up user authentication and navigated to the correct chat room, I ...

What is the best way to toggle buttons on and off with jQuery?

I've recently started a project for my class, and as a complete beginner in this field, I'm facing some challenges. My server is running on Ubuntu. In script.js, the following code is included: $(document).ready(function(){ $.get('/var/ ...

Angular: Retrieving the Time Format from the Browser

Is there a way to retrieve the time format from the operating system or browser within Angular in order to display time in the user's preferred format? I have attempted to search for a solution, but have come up empty-handed. Thank you in advance! ...

What is the correct way to set up a click event listener for a radio button?

Currently, I am in the process of dynamically generating HTML radio buttons. Each button is assigned an Id stored in a variable. My goal is to add a click event handler to these radio buttons using the assigned Id. However, I am encountering an issue where ...

Utilize PHP drop down menus for efficient data sorting and retrieval

On my website, there are two drop-down menus - one for courses and the other for students. I am trying to set it up so that when a course is selected from the first menu, only the students enrolled in that specific course will appear in the second dropdown ...

Using Javascript and Node.js to implement AI: Repeating a word from an array by using matching techniques

Seeking assistance with an AI project involving javascript and Node.js. I have set up hardcoded questions and answers, allowing users to modify the AI's responses. The majority of the javascript code has been implemented on the server-side. I am wor ...

How can you simultaneously map data from two SQL tables in React?

In my script, I am retrieving data from a SQL table called device and displaying it in a table by mapping the content of device. My goal is to include a column that fetches information from another SQL table, group, but I am struggling to adjust the mappin ...

How do I incorporate Spotify into my mobile app to enable seamless background music playback?

Currently engaged in a mobile app project that utilizes react-native for the frontend and nodeJS for the backend. The main objective is to enable users to seamlessly play Spotify songs directly within the app, even in the background. This enhancement will ...

What impact does incorporating a new test case have on code coverage in Jest?

I recently encountered an unexpected situation while working on a Jest test suite. Despite not making any changes to the codebase, I simply added a new test. Originally: mylibrary.js | 95.65 | 89.66 | 100 | 95.65 | 54-56,84 ------------ ...

I'm looking to create a post using two mongoose models that are referencing each other. How can I do this effectively?

My goal is to create a Post with the author being the user who created it and have the Post added to the array of posts in the user model that references "Post". Despite searching and watching tutorials, I'm still struggling to understand how to achie ...

Type parameters in TypeScript components

Below is the code snippet I am working with: const pageArea = (Component,title) => ({ ...props }) => { <Component {...props} /> } This works fine in JavaScript, but I am looking to convert it to TypeScript. This is what I have tried: functio ...