2

is it possible to import from a js string?

import(`alert("Hello")`);

which gives us more control over http fetching, like loading from protected url with access token.

PeiSong
  • 871
  • 1
  • 7
  • 12
  • It's not clear to me what's supposed to happen in your example. Why does the string contain JavaScript code? – Felix Kling Mar 21 '21 at 10:32
  • it's like fetch js file using axios api (with access token) then import the file string as module? – PeiSong Mar 21 '21 at 11:20
  • Am I right in assuming that you are fetching JS code as "text" because the access token is set in the header? And now you have to evaluate said text as JS module? – Felix Kling Mar 21 '21 at 20:19
  • yes exactly!!!! – PeiSong Mar 22 '21 at 00:43
  • `import` is used to import `modules`, hence it's pretty clear you can't use it to evaluate string values. You can read more on [dynamic imports here](https://2ality.com/2017/01/import-operator.html) - they can be used for conditional loading or load on demand, but they still have to be **modules** – Raul Rene Mar 22 '21 at 09:30
  • It might be possible to use [service workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) for that? I don't know if they also intercept `import` statements. – Felix Kling Mar 22 '21 at 12:55
  • Does this answer your question? [ES6 variable import name in node.js?](https://stackoverflow.com/questions/29168433/es6-variable-import-name-in-node-js) – Miroslav Papírník Mar 22 '21 at 13:23
  • The scenario is the remote js module is protected with access token. I guess I can only append token to url query string like import('module.js?token=xxxxx'); – PeiSong Mar 23 '21 at 08:23

0 Answers0