[英]JSX in Typescript without React
I tried to use typescript with jsx without react.我试图在没有反应的情况下使用带有 jsx 的打字稿。 and it doesn't work.
它不起作用。 I always put a
"jsx": "preserve"
in tsconfig.json.我总是在 tsconfig.json 中放一个
"jsx": "preserve"
。 But i dont understand what i have to do next.and when i am compiling .tsx file webpack throws an error但我不明白我接下来要做什么。当我编译 .tsx 文件时,webpack 抛出错误
ERROR in ./core/Navbar.tsx
Module parse failed: /home/ubuntu/Desktop/framework/node_modules/ts-loader/index.js!/home/ubuntu/Desktop/framework/core/Navbar.tsx Unexpected token (9:15)
ERROR in ./core/Navbar.tsx
Module parse failed: /home/ubuntu/Desktop/framework/node_modules/ts-loader/index.js!/home/ubuntu/Desktop/framework/core/Navbar.tsx Unexpected token (9:15)
You may need an appropriate loader to handle this file type.
i read the documentation but i dont understand how to use global jsx module in project.我阅读了文档,但我不明白如何在项目中使用全局 jsx 模块。 is it possible to use typescript + jsx without react?
是否可以在没有反应的情况下使用 typescript + jsx?
[ [
I just made this, maybe it could help我刚做了这个,也许它会有所帮助
export const JSX = {
createElement(name: string, props: { [id: string]: string }, ...content: string[]) {
props = props || {};
const propsstr = Object.keys(props)
.map(key => {
const value = props[key];
if (key === "className") return `class=${value}`;
else return `${key}=${value}`;
})
.join(" ");
return `<${name} ${propsstr}> ${content.join("")}</${name}>`;
},
};
export default JSX;
declare module JSX {
type Element = string;
interface IntrinsicElements {
[elemName: string]: any;
}
}
"jsx": "react",
"reactNamespace": "JSX",
import JSX from "./index";
function Hello(name: string) {
return (
<div className="asd">
Hello {name}
<div> Hello Nested </div>
<div> Hello Nested 2</div>
</div>
);
}
function log(html: string) {
console.log(html);
}
log(Hello("World"));
If you use jsx: prevserve, it means that the Typescript compiler will output .jsx files rather than compiling it down to .js, as a result, you will need something like Babel to transpile your jsx eventually since your browser can't run jsx files.如果您使用 jsx: prevserve,这意味着 Typescript 编译器将输出 .jsx 文件而不是将其编译为 .js,因此,您最终将需要 Babel 之类的东西来转译您的 jsx,因为您的浏览器无法运行 jsx文件。
To be honest, I'm not sure what you are trying to do, but you should either use jsx: react, or jsx: preserve + transpiler老实说,我不确定您要做什么,但是您应该使用 jsx:react 或 jsx:preserve + transpiler
Look at Stefan Baumgartners blog entry "JSX is syntactic sugar" .查看 Stefan Baumgartners 的博客条目“JSX 是语法糖” 。 It explains how to convert JSX to DOM elements at runtime using clean, easily readable code.
它解释了如何使用干净、易于阅读的代码在运行时将 JSX 转换为 DOM 元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.