Amna Irfan
Amna Irfan

Reputation: 94

Typescript [React] not converting .tsx imports to .jsx imports

I keep typescript react components in different files, so I use the following statement to import my sub components.

//app.tsx

import {SideBar} from "./sidebar"

But when typescript compiles app.tsx to app.jsx, the import statement switches to require("sidebar"). I get an error on the javascript as the require statement needs to have "sidebar.jsx" with ".jsx" extension. Is there a way I could automate that?

My tsconfig setting is :

{
    "compilerOptions": {
        "jsx": "preserve",
        "target": "ES5",
        "noImplicitAny":false,
		"module": "commonjs",
        
    }
}

Maybe I need to add something to the tsconfig file?

Thanks in advance.

Upvotes: 0

Views: 2291

Answers (1)

basarat
basarat

Reputation: 276229

Option 1

I get an error on the javascript as the require statement needs to have "sidebar.jsx" with ".jsx" extension.

Fix this error e.g. if you are using webpack you can add .jsx as a resolvable path.

resolve: {
  // Add `.jsx` as a resolvable extension.
  extensions: ['', '.webpack.js', '.web.js', '.jsx']
},

If so maybe even use ts-loader : https://github.com/TypeStrong/ts-loader and not have jsx: preserve and instead jsx: react. More : https://basarat.gitbooks.io/typescript/content/docs/jsx/tsx.html

Option 2

Use module: es6 instead of "module": "commonjs", and typescript will not rewrite import to require.

Upvotes: 0

Related Questions