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/libphonenumb[email protected]/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.

1

1 Answer 1

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/[email protected]/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/[email protected]/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>

Not the answer you're looking for? Browse other questions tagged or ask your own question.