Title: Tracking issue: Named imports from CJS module incorrectly allowed in nodenext · Issue #54018 · microsoft/TypeScript · GitHub
Open Graph Title: Tracking issue: Named imports from CJS module incorrectly allowed in nodenext · Issue #54018 · microsoft/TypeScript
X Title: Tracking issue: Named imports from CJS module incorrectly allowed in nodenext · Issue #54018 · microsoft/TypeScript
Description: This issue has come up a few times, most recently at DefinitelyTyped/DefinitelyTyped#65147 (comment), and I don’t think we’ve had a canonical place to explain, discuss, or track it. The symptom Sometimes, when you’re writing an ES module...
Open Graph Description: This issue has come up a few times, most recently at DefinitelyTyped/DefinitelyTyped#65147 (comment), and I don’t think we’ve had a canonical place to explain, discuss, or track it. The symptom Som...
X Description: This issue has come up a few times, most recently at DefinitelyTyped/DefinitelyTyped#65147 (comment), and I don’t think we’ve had a canonical place to explain, discuss, or track it. The symptom Som...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/54018
X: @github
Domain: github.com
IPv4 address: 140.82.114.4
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Tracking issue: Named imports from CJS module incorrectly allowed in nodenext","articleBody":"This issue has come up a few times, most recently at https://github.com/DefinitelyTyped/DefinitelyTyped/pull/65147#issuecomment-1515134407, and I don’t think we’ve had a canonical place to explain, discuss, or track it.\r\n\r\n## The symptom\r\n\r\nSometimes, when you’re writing an ES module in `--module nodenext`, you will want to import a CJS dependency, and TypeScript lets you used a named import:\r\n\r\n```ts\r\nimport { createProgram } from \"typescript\";\r\ncreateProgram(/* ... */);\r\n```\r\n\r\nbut Node complains:\r\n\r\n```\r\nfile:///project/out/main.mjs:1\r\nimport { createProgram } from \"typescript\";\r\n ^^^^^^^^^^^^^\r\nSyntaxError: Named export 'createProgram' not found. The requested module 'typescript' is a CommonJS module, which may not support all module.exports as named exports.\r\nCommonJS modules can always be imported via the default export, for example using:\r\n\r\nimport pkg from 'typescript';\r\nconst { createProgram } = pkg;\r\n```\r\n\r\nAlternatively but equivalently, you might try to use a namespace import:\r\n\r\n```ts\r\nimport * as ts from \"typescript\";\r\nts.createProgram(/* ... */);\r\n```\r\n\r\nand Node gives a much less helpful error:\r\n\r\n```\r\nfile:///project/out/main.mjs:2\r\nts.createProgram();\r\n ^\r\n\r\nTypeError: ts.createProgram is not a function\r\n```\r\n\r\nIn either case, you find that you instead need to write a default import:\r\n\r\n```ts\r\nimport ts from \"typescript\";\r\nts.createProgram(/* ... */);\r\n```\r\n\r\nBoth TypeScript and Node are happy with this, but why did TypeScript let you write the forms that crash at runtime?\r\n\r\n## The problem\r\n\r\nNode uses [cjs-module-lexer](https://github.com/nodejs/cjs-module-lexer) to syntactically analyze CommonJS modules without executing them in order to turn `module.exports` properties into named exports that can be imported as named (or namespace) imports by ES modules. However, syntactic analysis has its limitations, and not all `module.exports` properties get detected on all modules. (In practice, it’s common for this to be all-or-nothing, as with the `typescript` package in its current state: it has _no_ named exports available.)\r\n\r\nType definitions have no way of declaring which exports/properties of a CommonJS module will be detectable by Node’s named export analysis. In other words, `typescript.d.ts` is not misrepresenting the shape of the module; it would be impossible to “fix” it for Node ESM consumers without breaking it for CJS consumers or bundlers, which typically have more relaxed interop rules. TypeScript currently assumes that _all_ declared exports/properties of a CJS module will be detectable by Node and available as named imports. This is unsound, leading to the error in the example above.\r\n\r\nIt should be noted that at least for the _named_ import case, the crash occurs during Node’s module linking phase (as soon as the module graph is loaded—at startup, unless the affected part of the graph is isolated in a dynamic import), with a good runtime error message. While annoying to run into, it’s usually immediately diagnosable and fixable. The namespace import variation is a bit more insidious, since the import can be linked, but subsequent property accesses, which can occur later in execution, may fail.\r\n\r\n## Solutions and non-solutions\r\n\r\nI’m putting this issue up for tracking/documentation purposes, not to advocate for a fix. But it’s worth mentioning a few ways of addressing the problem since people will ask or suggest them:\r\n\r\n- We could make a flag that makes potentially unsafe named/namespace imports always error. It would be very cumbersome and catch a lot of false positives, but some people may prefer the safety over the convenience.\r\n- We could make it possible to annotate modules or individual exports/properties in type declarations that cannot be correctly analyzed by Node. This sounds pretty fraught and fragile to me, given how often people postprocess both their types and JS by third-party build tools.\r\n- We _cannot_ reasonably determine which exports/properties are detectable by Node by looking at the JS, e.g. by running cjs-module-lexer ourselves, because we never even resolve or read JS sources when types are found for them. Even without incurring the cost of running the (fast) lexer, the performance penalty for doing twice as much module resolution and file system hits would be unacceptable.","author":{"url":"https://github.com/andrewbranch","@type":"Person","name":"andrewbranch"},"datePublished":"2023-04-25T22:02:56Z","url":"https://github.com/microsoft/TypeScript/issues/54018"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:1f693702-b208-c669-6736-16ee5a863762 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 9F1A:3179F7:40954F:52D60B:6B04F74E |
| html-safe-nonce | c043224214c12aff050cc260459ac632481225aea37e0f423a0a1d0427298761 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5RjFBOjMxNzlGNzo0MDk1NEY6NTJENjBCOjZCMDRGNzRFIiwidmlzaXRvcl9pZCI6IjEwMzYyMzQ4NTEzNTcwOTU3NTgiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 6e9be1fe252fdc80d8316457304c0efa54c8c8b660d67454707210eb0d03d9d9 |
| hovercard-subject-tag | issue:1683938587 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/microsoft/TypeScript/54018/issue_layout |
| twitter:image | https://opengraph.githubassets.com/ed5622ad454ad6966349af48991536a9199556ce33f7ff2b4d1d7273dee6a182/microsoft/TypeScript/issues/54018 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/ed5622ad454ad6966349af48991536a9199556ce33f7ff2b4d1d7273dee6a182/microsoft/TypeScript/issues/54018 |
| og:image:alt | This issue has come up a few times, most recently at DefinitelyTyped/DefinitelyTyped#65147 (comment), and I don’t think we’ve had a canonical place to explain, discuss, or track it. The symptom Som... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | andrewbranch |
| hostname | github.com |
| expected-hostname | github.com |
| None | 2c3971d6ab4be607cf9a26ac26ef0a7bfce380ec2ba14642e64028ad07a492b9 |
| turbo-cache-control | no-preview |
| go-import | github.com/microsoft/TypeScript git https://github.com/microsoft/TypeScript.git |
| octolytics-dimension-user_id | 6154722 |
| octolytics-dimension-user_login | microsoft |
| octolytics-dimension-repository_id | 20929025 |
| octolytics-dimension-repository_nwo | microsoft/TypeScript |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 20929025 |
| octolytics-dimension-repository_network_root_nwo | microsoft/TypeScript |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | b3f1d45dee14b3f87c64e9017a9c08d011561786 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width