简体   繁体   中英

JSX in Typescript without React

I tried to use typescript with jsx without react. and it doesn't work. I always put a "jsx": "preserve" in tsconfig.json. But i dont understand what i have to do next.and when i am compiling .tsx file webpack throws an error

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. is it possible to use typescript + jsx without react?

在此处输入图片说明 my App.tsx class

[ 我的 App.tsx 类 [2]

error when webpack compile file 控制台错误

I just made this, maybe it could help

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",

test it

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.

To be honest, I'm not sure what you are trying to do, but you should either use jsx: react, or jsx: preserve + transpiler

Look at Stefan Baumgartners blog entry "JSX is syntactic sugar" . It explains how to convert JSX to DOM elements at runtime using clean, easily readable code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM