0

How can I import 2 objects with the same name but conditionally use them on the page

I tried this, but import can be only on top so it doesn't work

if (window.location.href.includes('showcase')) {
  import { Tags } from "../../../data/folder1";
} else {
  import { Tags } from "../../../data/folder2";
}

I tried also this but I'm stuck:

 import { Tags } from "../../../data/folder1"
 import { Tags } from "../../../data/folder2"

const PageTags = window.location.href.includes('showcase') ? Tags : Tags <=== issue here

Fill
  • 377
  • 2
  • 15
  • 1
    [Dynamic import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports) - ps: probably best used alongside top-level-await. – ASDFGerte Feb 02 '22 at 13:13
  • There has to be a good original for this... – T.J. Crowder Feb 02 '22 at 13:14
  • E.g.: ```const { Tags } = await import(`../../../data/${window.location.href.includes('showcase') ? "folder1" : "folder2"}`);``` Note that some bundlers may not support entirely dynamic imports like this, though modern browders do. – T.J. Crowder Feb 02 '22 at 13:17
  • 1
    Re your attempt at the end, if you're really okay with importing them both and then only using one, you could use import renaming: `import { Tags as Tags1 } from "../../data/folder1"; import { Tags as Tags2 } from "../../data/folder2"; const Tags = window.location.href.includes("showcase") ? Tags1 : Tags2;` – T.J. Crowder Feb 02 '22 at 13:26
  • 1
    Amazing, thank you @T.J.Crowder – Fill Feb 02 '22 at 13:30
  • 1
    FWIW, I cover renaming (and dynamic import) in my recent book *JavaScript: The New Toys* (Chapter 13). Links in my profile if you're interested. Happy coding! – T.J. Crowder Feb 02 '22 at 13:33

0 Answers0