Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamic Typescript import can only be static #5242

Closed
Javarome opened this issue Oct 14, 2020 · 1 comment
Closed

Dynamic Typescript import can only be static #5242

Javarome opened this issue Oct 14, 2020 · 1 comment

Comments

@Javarome
Copy link

🐛 bug report

When using the dynamic import syntax in Typescript code, only a constant file name can be referenced.
Using a variable does not transpile to correct module resolving.

🎛 Configuration (.babelrc, package.json, cli command)

  • No specific babel configuration
  • package.json:
{
  "name": "vanilla-typescript",
  "main": "index.html",
  "scripts": {
    "start": "parcel index.html --open"
  },
  "dependencies": {},
  "devDependencies": {
    "parcel-bundler": "^1.6.1",
    "typescript": "^4.0.3"
  }
}
  • tsconfig.json:
{
  "compilerOptions": {
    "strict": true,
    "module": "esnext",
    "jsx": "preserve",
    "esModuleInterop": true,
    "sourceMap": true,
    "allowJs": true,
    "lib": [
      "dom",
      "esnext"
    ],
    "target": "ES2018",
    "rootDir": "src",
    "moduleResolution": "node"
  }
}

🤔 Expected Behavior

Dynamic import should work the same when using either a constant file name or a variable file name.

😯 Current Behavior

when using import(fileVar) the file is not found as attempted to be loaded as is, without resolution.
This is because that code part is left as is, not transpiled the way as when import("fileConstant").

Uncaught (in promise) TypeError: Failed to fetch dynamically imported module: http://localhost:1234/dir/someTsFile
Promise.then (async)
parcelRequire.src/index.ts../user/User @ index.ts:85
newRequire @ src.f10117fe.js:47
(anonymous) @ src.f10117fe.js:81
(anonymous) @ src.f10117fe.js:120

💁 Possible Solution

The code with a variable should be transpiled the same way as the code with a constant:

const fileVar = "./dir/someTsFile"
require("_bundle_loader")(require.resolve(fileVar)).then(...)

🔦 Context

This allows lazy loading but prevents any real dynamic loading, where the name/path of module to load depends on runtime (from a user choice, typically).

💻 Code Sample

const fileVar = "./dir/someTsFile";
import(fileVar).then(...)

🌍 Your Environment

Software Version(s)
Parcel 1.12.4
Node 14.8.0
npm/Yarn 6.14.8
Operating System MacOS 10.15.7
@mischnic
Copy link
Member

Duplicate of #125

@mischnic mischnic marked this as a duplicate of #125 Oct 14, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants