Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

enter image description here my App.tsx class

[my App.tsx class[2]

error when webpack compile file console error

like image 572
Fuad Ibrahimov Avatar asked Oct 14 '16 19:10

Fuad Ibrahimov


1 Answers

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"));
like image 194
Daniel Pérez Avatar answered Sep 19 '22 23:09

Daniel Pérez