20

How can I import a static url using webpack:

index.js

import 'http://google.com/myscript.js'

eguneys
  • 6,028
  • 7
  • 31
  • 63

3 Answers3

10

It's really unclear what you're trying to do, but in general you have a few options.

  1. Pre-download the script or install it via NPM. This probably is the preferred way to deal with external dependencies. Once it is local you can easily import or require it like any other module.

  2. If it absolutely must be loaded dynamically you will need a 3rd party module such as https://www.npmjs.com/package/scriptjs which can easily download 3rd party modules at runtime and block the execution of the rest of the script until it has been parsed.

  3. Use a <script> tag and include it on your page. This only works if it's a general dependency that can be loaded before everything else (maybe for a polyfill or a library you depend on everywhere like jquery.)

I hope that helps!

Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50
1

This webpack issue says you can use this comment to allow the import to just work. Though this is only dynamic import not static.

import(/* webpackIgnore: true */ "https://example.com");

First seen here https://stackoverflow.com/a/69951351/4619267

J Decker
  • 537
  • 5
  • 9
  • This disables any webpack processing and just let the browser to handle `import` nativelly, as most browsers now can: https://stackoverflow.com/questions/34607252/es6-import-module-from-url/70750023#70750023. This is the answer as of 2023. – AxeEffect May 17 '23 at 12:05
  • @AxeEffect. That may be true for JS files, but what about TypeScript? – jordanbtucker Aug 27 '23 at 22:45
-3

import is es6. With es5 and webpack, use require, or better wrap your JS files with AMD/UMD.

jlchereau
  • 1,152
  • 1
  • 7
  • 5