Description
Suggestion
These days - nodejs supports esm/commonjs interop by allowing dynamic import expressions inside of cjs modules. Currently, this is the only way to import/require pure ESM packages inside of commonjs based projects. Refactoring a project to pure ESM is not always possible. Some popular open source maintainer are forcing use of pure ESM (ie.. @sindrsorhus)
🔍 Search Terms
module modules import require commonjs esm esm interop export default exports await import import( import() dynamic imports
✅ Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript codeThis wouldn't change the runtime behavior of existing JavaScript codeThis could be implemented without emitting different JS based on the types of the expressionsThis isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)This feature would agree with the rest of TypeScript's Design Goals.
⭐ Suggestion
Add an escape hatch - perhaps by a comment flag or configuration option to allow dynamic imports in project compiling to commonjs.
📃 Motivating Example
Set compilerOptions.module to "commonjs"
case:1
// error
import meow from 'meow';
case:2
// currently an error
(async () => { const meow = await import('meow') });
compiles to something like const meow = await Promise.resolve(require('meow'))
// after adding a new option to allow dynamic imports case2 would not transform dynamic import expressions while import statements would compile to require.
(async () => { const meow = await import('meow') });
💻 Use Cases
This would allow to use TS using current Node.JS capabilities and native modules more naturally as well as support more libraries for NodeJs without having to use something like webpack to achieve.
Activity
andrewbranch commentedon Jul 21, 2021
@weswigham I assume this is already handled in one of your recently merged or soon-to-be-merged
--module=node12
PRs?andrewbranch commentedon Jul 21, 2021
Assigning and milestoning for now, but I’m pretty sure this is already done or in the works
weswigham commentedon Jul 21, 2021
Aye - the
node12
module mode as is currently in PR supports this.import
function from a CommonJS module. #52775package.json
contents when creatingtsconfig.json
undertsc --init
to determine better defaults #51207