Use React TSX tags without having to write "import React from 'react'"
See original GitHub issueSuggestion
I have to write import React from 'react'
every time I use TSX syntax even though I make no explicit mention of the name React
in the following lines of code (Of course, TSC output will contain mentions of React
but the key is explicit).
It is possible to write JSX tags in Babel’s JavaScript without import React from 'react'
by using Babel’s/Webpack’s plugins. A notable example is Next.js.
Therefore I suggest: If user are not mentioning React
directly, user shouldn’t have to declare React
explicitly. This can be configured in compiler options, something like a combination of --jsxFactoryPath
and --jsxModule
for example.
Examples
React.js
Ideal Source Code
tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"jsxFactoryPath": ["createElement"],
"jsxModule": "react"
}
}
index.tsx:
export = <div id='123'>hello</div>
Desired Output
index.js:
var _jsx = require("react").createElement;
module.exports = _jsx("div", { id: "123" }, "hello");
Hyperscript
Ideal Source Code
tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"jsxFactoryPath": [],
"jsxModule": "hyperscript"
}
}
index.tsx:
export = <div id='123'>hello</div>
Desired Output
var _jsx = require("hyperscript");
module.exports = _jsx("div", { id: "123" }, "hello");
Generic
Ideal Source Code
tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"jsxFactoryPath": ["obj1", "obj2", "func"],
"jsxModule": "pkg/dir1/dir2"
}
}
index.tsx:
export = <div id='123'>hello</div>
Desired Output
index.js:
var _jsx = require("pkg/dir1/dir2").obj1.obj2.func;
module.exports = _jsx("div", { id: "123" }, "hello");
Checklist
My suggestion meets these guidelines:
- This wouldn’t be a breaking change in existing TypeScript / JavaScript code
- This wouldn’t change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn’t a runtime feature (e.g. new expression-level syntax)
Issue Analytics
- State:
- Created 5 years ago
- Reactions:5
- Comments:11 (6 by maintainers)
Top GitHub Comments
I said this and this.
Gotcha, just giving my own opinion. 😃