Is there a way to import a Javascript file from a URL (relative) in the browser from Javascript code?
I know you can import a Javascript file from HTML but I don’t want to do that.
I would expect something like this:
import { functionName } from "/static/javascript/fileName";
functionName();
>Solution :
Yes, relative URLs are absolutely fine. A couple of things to note:
- Like all other relative URLs in the browser environment, they’re resolved client-side.
- Your
importis syntactically correct, but you probably meant to have.json there, because browsers do not add file extensions for you.
If your import were in a file at https://example.com/something/somefile.js, your import would be telling the browser to import from https://example.com/static/javascript/fileName.
Guessing a bit from the name of your path, you probably wanted:
import { functionName } from "./fileName.js";
That tells the browser to import from fileName.js on the same path as the JavaScript file the import occurs in. So if the import were in https://example.com/something/somefile.js, the browser would look for https://example.com/something/fileName.js.