Jhuang Chen
Jhuang Chen

Reputation: 15

JS npm package, Cannot use import statement outside a module

I wanted to use this npm package https://github.com/nefe/number-precision, follow the steps but not working.

  1. npm install number-precision --save--dep

  2. import NP from 'number-precision' orrequire() on my JS file first-line , the error message will like this : Cannot define require && export or Cannot use import statement outside a module.

  3. <script src="node_modules/number-precision/build/index.iife.js">import NP from 'number-precision </script>

    It won't show any error message but in my js file, NP method still doesn't work.

  4. <script src="/workout.js"></script> and put on my js file first-lineimport NP from 'number- precision'

    I got this:

    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 do I correctly execute this npm package in my js file?

Upvotes: 0

Views: 813

Answers (2)

connexo
connexo

Reputation: 56754

To use imports in the browser, the file that does the imports needs to

a) be included with type="module":

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

b) it only works for scripts that are remote (that is, have a src attribute), it does not work for inline scripts.

Also note that you cannot shorthand reference files from node_modules in the browser, that only works when run with Node.

So, inside your workout.js, start like this:

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

Unfortunately, that library author does not seem to supply a true ES6 module version (I've just opened an issue on that), so you cannot proceed like the page suggests and import the script into a variable NP.

Executing the script like the import shown above should work for you, though, and expose the library in the global namespace.

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370729

If you want to use the standalone <script> tag, look at 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;

}({}));

It creates a global NP variable, so no importing is necessary, just put this first:

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

(change the src if needed, to the right path to your index.iife.js, however you want to structure it)

If you want to use this with Webpack, it works fine for me. After installing the package, import it in your entry point:

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

and then run Webpack to bundle the code:

npx webpack

and a working bundle will be produced in dist/main.js (or somewhere similar). Then link that bundle on your site.

Upvotes: 0

Related Questions