没有 React 的 Typescript 中的 JSX

Fua*_*mov 5 javascript typescript reactjs

我试图在没有反应的情况下使用带有 jsx 的打字稿。它不起作用。我总是"jsx": "preserve"在 tsconfig.json 中放一个。但我不明白接下来我必须做什么。当我编译 .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)

You may need an appropriate loader to handle this file type. 我阅读了文档,但我不明白如何在项目中使用全局 jsx 模块。是否可以在没有反应的情况下使用 typescript + jsx?

在此处输入图片说明 我的 App.tsx 类

[我的 App.tsx 类 [2]

webpack 编译文件时出错 控制台错误

Dan*_*rez 6

我刚做了这个,也许它会有所帮助

索引.tsx

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;
Run Code Online (Sandbox Code Playgroud)

外部.d.ts

declare module JSX {
  type Element = string;
  interface IntrinsicElements {
    [elemName: string]: any;
  }
}
Run Code Online (Sandbox Code Playgroud)

配置文件

"jsx": "react",
"reactNamespace": "JSX",
Run Code Online (Sandbox Code Playgroud)

测试一下

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"));
Run Code Online (Sandbox Code Playgroud)


lua*_*ped 3

如果你使用 jsx: prevserve,这意味着 Typescript 编译器将输出 .jsx 文件,而不是将其编译为 .js,因此,你最终将需要像 Babel 这样的东西来转译你的 jsx,因为你的浏览器无法运行 jsx文件。

老实说,我不确定你想做什么,但你应该使用 jsx:react 或 jsx:preserve + transpiler