Issue with JS npm package: Unable to use import statement outside a module

I recently attempted to utilize the npm package found at https://github.com/nefe/number-precision. However, despite following the prescribed steps, I encountered some difficulties.

  1. After running

    npm install number-precision --save--dep
    , I tried importing NP from 'number-precision' in my JS file first-line. Unfortunately, I received error messages such as "Cannot define require && export" or "Cannot use import statement outside a module."

  2. I also attempted including

    <script src="node_modules/number-precision/build/index.iife.js">import NP from 'number-precision </script>
    in my HTML file. Although no error message appeared, the NP method still did not function in my JS file.

  3. I then added

    <script src="/workout.js"></script>
    and specified
    import NP from 'number-precision'
    on the first line of my JS file. This resulted in an error message stating: "refused to execute script from 'http://0.0.0.0:2000/node_modules/number-precision/' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled." How can I properly implement this npm package in my JS file?

Answer №1

If you want to use imports in the browser, make sure that the file performing the imports is included with the attribute type="module":

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

This method only works for remote scripts (those with a src attribute) and does not apply to inline scripts.

Keep in mind that referencing files from node_modules directly in a browser environment is not supported; this functionality is specific to Node.js.

To start using imports in your workout.js file, follow this pattern:

import 'https://github.com/nefe/number-precision/blob/master/build/index.iife.js';

Although the library author may not provide a true ES6 module version (as discussed in this issue), importing the script as demonstrated above should still work, allowing you to access the library via the global namespace.

Answer №2

To utilize the standalone <script> tag, check out the content of the iife.js:

https://github.com/nefe/number-precision/blob/master/build/index.iife.js

var NP = (function (exports) {
'use strict';

// ...

return exports;

}({}));

This creates a global variable called NP, so importing is not needed. Simply include this first:

<script src="./index.iife.js"></script>

(adjust the src if necessary to point to your index.iife.js correctly and in your preferred structure)

If you prefer using it with Webpack, it functions well for me. Install the package, then import it in your main entry file:

// src/index.js
import NP from 'number-precision'
console.log(NP.round(5, 5));

Subsequently, run Webpack to bundle the code:

npx webpack

A functional bundle will be generated at dist/main.js (or similar location). Link this bundle on your website afterwards.

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

Having trouble accessing HikVision Web SDK functions in Angular 17

First and foremost, this concerns the HikVision cameras specifically. Because the SDK is compiled to plain JavaScript (with jQuery included), I had to import the JS files in angular.json and use declare in the component TS file (in this instance, camera.c ...

Experiencing the 'invalid_form_data' error while attempting to upload a file to the Slack API via the files.upload method in Angular 8

I am currently working on a project that involves collecting form data, including a file upload. I am trying to implement a feature where the uploaded file is automatically sent to a Slack channel upon submission of the form. Despite following the guidance ...

CSS Flexibility

Greetings everyone, it's been a while since I dabbled in web development. I recently worked on my site with the intention of making it responsive using flexbox. This is my first time posting here, so please guide me on how to seek help more effective ...

What strategies can I employ to access data from an Ajax POST call beyond its original return function?

I am facing an issue with my jQuery Ajax POST call that runs a PHP script and retrieves data. The problem lies in accessing this data outside the success function. Even though I have declared a global variable components, it seems to lack scope within the ...

How can we efficiently add a new node to a polyline link in gojs while maintaining the original positions of points in the links adjacent to the inserted node

After posting a question on StackOverflow (Seeking Javascript library for displaying and editing networks of nodes and edges), I was directed to the gojs splice sample. The sample has been helpful, but I've hit a roadblock trying to achieve the speci ...

Having trouble populating a dropdown menu with states based on a selected country in real time

I'm attempting to create a dynamic dropdown where selecting a country will populate the states. I have all the necessary data stored in two tables, but I'm unsure how to proceed. While I can easily generate the initial list of countries, handling ...

What is preventing the JQuery dialog from opening?

When I try to trigger a dialog box by pressing the enter key, it is not working as expected. Instead of opening the dialog, it just hides the text. Can someone help me understand what might be causing this issue? <!doctype html> <html lang="en" ...

Create a randomly generated value in a JSON format

{ "description": "AppName", "name": "appName", "partnerProfile": { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f19090b1969c90989ddf929e9c">[email protected]</a>", "firstName": "John", ...

Vue.js2 - Detection of Observer in Array

A question for beginners in vue.js. I am trying to display data using the CanvasJS Library that is received via websocket. Everything works fine with the data until I introduce vue components into the mix. Let me clarify: export default { data() { r ...

Looking for assistance in reducing the vertical spacing between divs within a grid layout

Currently, I am in the process of developing a fluid grid section to showcase events. To ensure responsiveness on varying screen resolutions, I have incorporated media queries that adjust the size of the div elements accordingly. When all the divs are unif ...

Output text in Javascript (not to the console)

I'm on the lookout for a way to welcome a user by their name when they enter it into a JavaScript application. I have tried this code snippet: function getname() { var number = document.getElementById("fname").value; alert("Hello, " + fnam ...

Click and release file upload

I am working on creating a drag and drop upload feature where the user can drop files onto a div, and then click an upload button to send them to the server. I'm facing an issue with JavaScript not recognizing the variable fd. How can I pass that vari ...

Display and conceal various elements in Vue.js using a data list

I'm a beginner in Vue.js, currently using Vue+Webpack. I am trying to make each link display data based on their respective ids when clicked, and match with the show attribute. I have created this functionality in a .vue file. export default { el ...

Can the second function be modified to incorporate the first one's syntax?

export const composeValidators = (...validators) => value => validators.reduce((error, validator) => error || validator(value), undefined); export const composeAccreditionValidators = (...validators) => value => validators.reduce((error, va ...

Enhance the express Response type and then export my updated type as a distinct module

I am currently working on developing a new 'common' module for my team. One of the key features it should have is an extension of both the response and request objects in Express. Our main goal is to achieve two things - first, extending the Req ...

Disabling the Bootstrap tooltip feature is a quick and easy process

Is there a way to turn off bootstrap tooltip on my website? I activated it with the code below: function activateTooltip() { const toolTips = document.querySelectorAll('.tooltip'); toolTips.forEach(t => { new bootstrap.Tooltip(t); } ...

Ways to manage a post request in Next.js

Attempting to establish a POST route within my api directory with next.js. After sending the data to the route, I am having difficulty parsing the data in order to properly store it in the database. What would be the most effective approach for managing ...

elimination of nonexistent object

How can I prevent releasing data if two attributes are empty? const fork = [ { from: 'client', msg: null, for: null }, { from: 'client', msg: '2222222222222', for: null }, { from: 'server', msg: 'wqqqqqqqq ...

Does the onchange function in the dropdown list only work when the first item is changed?

Here is a snippet of my HTML code featuring a list item generated from a database using a foreach loop: <select class="form-control select" id="inventoryitem" name="inventoryitem" onchange="getunit();"> <option>---Select an item---</o ...

Executing a secondary API based on the data received from the initial API call

Currently, I am diving into the world of RxJS. In my project, I am dealing with 2 different APIs where I need to fetch data from the first API and then make a call to the second API based on that data. Originally, I implemented this logic using the subscri ...