首页 文章

没有React的Typescript中的JSX

提问于
浏览
2

我尝试使用带有jsx的typescript而没有反应 . 它不起作用 . 我总是把 "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而不做出反应?

enter image description here
我的App.tsx类

[
my App.tsx class2

webpack编译文件时出错
console error

2 回答

  • 2

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

    说实话,我不确定你要做什么,但你应该使用jsx:react,或者jsx:保留transpiler

  • 0

    我刚刚做了这个,也许它可以提供帮助

    index.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;
    

    external.d.ts

    declare module JSX {
      type Element = string;
      interface IntrinsicElements {
        [elemName: string]: any;
      }
    }
    

    tsconfig.json

    "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"));
    

相关问题