How to use unpkg url-join.js as <script src=…> import?

Issue

I’m trying to use urlJoin in my project. I’ve imported the library/script using <script> tag as the HTML is generated by Django.

<script src="https://unpkg.com/url-join@5.0.0/lib/url-join.js"></script>

The problem is that I can’t use urlJoin function – the console says:

urlJoin
VM609:1 Uncaught ReferenceError: urlJoin is not defined
    at <anonymous>:1:1

The function is defined like this:

export default function urlJoin() {
  var input;

  if (typeof arguments[0] === 'object') {
    input = arguments[0];
  } else {
    input = [].slice.call(arguments);
  }

  return normalize(input);
}

Do you know how to use it?

Solution

The file is an ES6 module. See JavaScript modules on MDN.

You need to:

  • Mark the script where you use urlJoin as a module
  • import it into that script
  • Not have a separate <script> element to load urlJoin.

Thus:

<script type="module">
  import urlJoin from "https://unpkg.com/url-join@5.0.0/lib/url-join.js"; 
  const foo = urlJoin("some", "args"); 
  console.log(foo);
</script>

Answered By – Quentin

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.