Last active
January 7, 2024 03:59
-
-
Save chrisgervang/59ed046c0a8d7c3a1be1b3416f8f2466 to your computer and use it in GitHub Desktop.
Understanding Typescript: "allowSyntheticDefaultImports": true
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// React doesn't use es2015 "export default react" syntax in their NPM dist. | |
// Instead they set a "default" key in their export object. | |
/** node_modules/react/cjs/react.development.js | |
... | |
var React$2 = Object.freeze({ | |
default: React | |
}); | |
var React$3 = ( React$2 && React ) || React$2; | |
// TODO: decide on the top-level export form. | |
// This is hacky but makes it work with both Rollup and Jest. | |
module.exports = react; | |
*/ | |
// This works since this is what "export default React" changes to at build time with almost every build system today, but it isn't following the es2015 or esnext module spec. | |
// The typescript definition for react is written to match how react is written, and doesn't use "export default React". | |
// The Typescript Type Checker by default is expecting modules to follow the spec, so to import React we all have to do.. | |
/** tsconfig.json | |
{ | |
"compilerOptions": { | |
... | |
"module": "esnext", | |
"moduleResolution": "node", | |
} | |
} | |
*/ | |
import * as React from 'react'; // sad face | |
// But since this rule is broken by so many modules (for legit reasons), the type checker can be set up to work with it by adding allowSyntheticDefaultImports. | |
/** tsconfig.json | |
{ | |
"compilerOptions": { | |
... | |
"allowSyntheticDefaultImports": true | |
} | |
} | |
*/ | |
// This works now! | |
import React from 'react'; | |
/** | |
Note this only changes the behavior of the type checker. So whatever you're using to compile (tsc / babel) | |
and bundle (webpack / gulp) will independently need to be set up to handle this correctly. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment