0

Just to play around with some package functions I want to import it into my browser's console. I have tried this approach, but it gives a parsing error.

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://unpkg.com/libphonenumber-js@1.7.26/core/index.js';
document.head.appendChild(script);

The errror I am getting,

parsePhoneNumberFromString.js:1 Uncaught SyntaxError: Cannot use import statement outside a module

I am trying to use parsePhoneNumberFromString function into my browser's console.

Hafiz Temuri
  • 3,882
  • 6
  • 41
  • 66
  • Possible duplicate of [How to use ES6 modules from dev tools console](https://stackoverflow.com/questions/52569996/how-to-use-es6-modules-from-dev-tools-console) – Patrick Evans Nov 18 '19 at 19:09

1 Answers1

1

You don't use <script> tags to import modules like that, or if you do, you do it within the script itself using an import statement like import * as reduxSaga from "https://unpkg.com/redux-saga@1.0.3/dist/redux-saga-effects.esmodules-browsers.js".

The key thing is to set the type on the <script> tag so that it is type="module" that way it knows to load the script as a module (which allows import export).

For example:

index.js

import {parsePhoneNumberFromString} from "https://unpkg.com/libphonenumber-js@1.7.26/core/index.js";

const pnStr = "555-555-5555";
const pn = parsePhoneNumberFromString(pnStr);
console.log(pn);

index.html

<html>
    <head>
        <script src="index.js" type="module"></script>
    </head>
</html>
zero298
  • 25,467
  • 10
  • 75
  • 100