ChatGPT解决这个技术问题 Extra ChatGPT

Cannot use JSX unless the '--jsx' flag is provided

I have looked around a bit for a solution to this problem. All of them suggest adding "jsx": "react" to your tsconfig.json file. Which I have done. Another one was to add "include: []", which I have also done. However, I am still getting the error when I am trying to edit .tsxfiles. Below is my tsconfig file.

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "allowJs": true,
        "checkJs": false,
        "jsx": "react",
        "outDir": "./build",
        "rootDir": "./lib",
        "removeComments": true,
        "noEmit": true,
        "pretty": true,
        "skipLibCheck": true,
        "strict": true,
        "moduleResolution": "node",
        "esModuleInterop": true
    },
    "include": [
        "./lib/**/*"
    ],
    "exclude": [
        "node_modules"
    ]
}

Any suggestions would be helpful. I am using babel 7 to compile all the code with the env, react and typescript presets. If you guys need more files to help debug this, let me know.

It's unclear what the problem is. babel 7 to compile all the code with the env, react and typescript presets - why are there both Babel and TS and how are they related? I am still getting the error - which one? "jsx": "react" - Note: The identifier React is hard-coded, so you must make React available with an uppercase R

P
Pardeep Jain

Every time I run npm start, it overrides whatever I configure in {jsx: ...} with react-jsx in order to be compatible with JSX transform in React 17.

The following changes are being made to your tsconfig.json file:
  - compilerOptions.jsx must be react-jsx (to support the new JSX transform in React 17)

The problem is VSCode using an older version of typescript (4.0.3), while the typescript version shipped with the project is (4.1.2).

The following did the trick for me:

Go to the command palette CTRL+Shift+P (Or ⌘+Shift+P on Mac). Choose "TypeScript: Select a TypeScript Version...". Choose "Use workspace Version".

https://i.stack.imgur.com/Ro3a0.png

https://i.stack.imgur.com/Iwcaw.png

https://i.stack.imgur.com/0oo6Y.png

PS: This option doesn't show though unless you're on any .tsx file (thanks @awran5 for your comment and good catch)


Thanks, that worked for me. This option doesn't show though unless you're on any .tsx file.
Yes, and in case your app is not in the top-level folder of your workspace you can configure the typescript directory as described at code.visualstudio.com/docs/typescript/…
I don't even get the option to change the typescript version to the workspace version. I only get the VS Code version of 4.0.3, even though I have 4.1.2 installed.
This worked for my, just had to change react-jsx back to react.
Thanks! I was searching for an answer. Helped me a lot
b
basarat

Cannot use JSX unless the '--jsx' flag is provided

Restart your IDE. Sometimes tsconfig.json changes aren't immediately picked up 🌹


The error remains on my machine. Looks like "jsx": "react-jsx" is not a valid value. I get the following error Argument for '--jsx' option must be : 'preserve', 'react-native', 'react'. But create-react-app sets it to "react-jsx". What should I do?
You can also tell VS Code to use a specific version of TypeScript in a particular workspace by adding a typescript.tsdk workspace setting pointing to the directory of the tsserver.js file: "typescript.tsdk": "./node_modules/typescript/lib" code.visualstudio.com/docs/typescript/…
Changing the version did the trick ! Take a look at the answer below :)
I changed tsconfig.json, and it worked, { ..... "jsx": "react" }, "include": [ "src", "/node_modules/**/*" ] }. Modified "jsx:react" and added "node_modules/**/*".
haha wow I thought surely there was some configuration issue and spent an extra 10 minutes trying to debug after reading this answer- but yep, this was it
M
Mel Macaluso

For whoever reading, go to the tsconfig.json and change that line from react-jsx to react:

{
  "compilerOptions": {
    "jsx": "react"
  }
}

bonus: try also setting the IDE TS version to the latest (atm 4.2), in vscode CMD + SHIFT + P and change it from there.


unfortunately after you run yarn start or npm start it will return back to "react-jsx" :(
"jsx": "react" was missing from my tsconfig. Added it and fixed the problem.
This is give me a react umd global error. One of the solution is putting back to react-jsx. I'm stucked in infinity loop of errors.
"jsx": "preserve" did work for me (I'm using babel and webpack along with)
this is missing the point, react-jsx is the newer transform. That comes with a host of improvements. so blanket, remove this, is hiding a lot of complexity
G
Gabriel Petersson

create-react-app is broken out of the box. AS OF 2022 MAY

Inside of tsconfig, include was set only to /src, Change to:

  "include": [
    "./src/**/*.ts"
  ]

Yeah I had the same setup also
I dont even get the option to change the typescript version to the workspace version. I only get the VS Code version of 4.0.3, even though I have 4.1.2 installed.
@Sapper6fd, yeah same. the creator of react-create-app talked about mismatch of vscode typescript and project typescript, might need to separately update vscode/its typescript?
and .tsx maybe?
I guess create-react-app is great starting point)
R
Raydot

In my case, the issue was that VSCode generated an empty tsconfig.json file which, of course, did nothing.

I added this to tsconfig.json from Typescript's React Page:

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es6",
        "jsx": "react"
    }
}

...then hit save and VSCode took it from there.


How is this not upvoted more?! This change fixed all the errors after running the audit fix that updated to expo@1.0.0.
R
Raj

April 2021, and this issue still persist. I am using react-boilerplate-cra-template with react 17.02.

This is an issue with VSCode, it uses its in-built typescript by default. You just need to open a .tsx file and

Press: Ctrl + Shift + P Enter: Typescript: Select typescript version... Select: Use workspace version.


this worked for like 5 seconds before it reverted back to the old version, still no solution on my end
K
Karl Taylor

If you are seeing this issue after running create-react-app with Typescript You can solve this problem by adding "typescript.tsdk": "node_modules/typescript/lib" to .vscode/settings.json.

For IntelliSense, if you use "jsx": "react-jsx" you need to switch your workspace to use TS 4.1+

Or visually, simply go down to the blue task bar and select the Typescript version (Probably 4.x.x something), then select "Select TypeScript Version".

https://i.stack.imgur.com/CS34O.png

Then select "Use Workspace Version version" which should reference node_modules/typescript/lib

https://i.stack.imgur.com/w6nZ3.png


The preferable solution - change your IDE setting instead of changing your appplication! +1
G
GorvGoyl

adding "jsx": "react" to jsconfig.json didn't work for me but "jsx": "preserve" did:

jsconfig.json / tsconfig.json:

{
  "compilerOptions": {
    "jsx": "preserve"
  }
}

Thanks, I had this issue on VStudio rather than actual compilation or running time
R
RonniePettyII

This answer is regarding VS Code and this particular error persisting in that IDE. (Someone may find this useful)

If you're using something like Webpack or some other such tooling you may still get this error even if your tsconfig has the compiler option for jsx set to React.

There is a solution to this. The problem is VS Code has built in auto detection for tsc.

To get rid of the error in the editor you can put this in your User Settings:

{
    "typescript.tsc.autoDetect": "off"
}

Just note that you will no longer get tsc auto detection but if you're primarily using tooling like Webpack or handling the command yourself with flags then this isn't that big of a deal.

Note: Only do this if the error is persisting in VS Code. To ensure this behavior is persisting reload the windows and restart the editor after configuring your tsconfig.json file.


b
bluenote10

I was getting this error even when running npx tsc --jsx preserve so the --jsx was definitely specified.

In my case this was caused by having incremental: true in the tsconfig. Apparently in incremental mode tsc may ignore the --jsx setting, and use information from previous builds instead (where --jsx was still disabled). As a solution I turned of incremental compilation temporarily, recompiled, and re-enabled it. Probably deleting the build artifacts might also work.


That was my case. Your answer helped
F
FireFly0

Restarting my IDE in my case was the fix.After restarting a message box popped up and it was showing that i don't have any typescript installed, would you like to install TypeScript 3.3? I installed it and now its working perfectly.See here for output window


P
Petras V.

To solve this for all future projects, you can install JavaScript and TypeScript Nightly extension for VSCode.


J
João Augusto Tonial Laner

I my case none of the solutions were working, so I looked the version of ECMA Scrypt. My version was ec5, you can check here -> tsconfig.json. So I tried to switch the target: "es5" to target: "es2017" an it seems to handle the problem, with anything comes up again, I'll edit this comment


L
Long Do Thanh

For those who use Visual Studio 2019, you can fix it by doing all following:

In tsconfig.json, have this part

"include": [
    "./src/**/*.ts"
]

Update Typescript sdk in C:\Program Files (x86)\Microsoft SDKs\TypeScript I had had version 4.0. I needed to update it to 4.1 (more clearly, 4.1.2) by deleting the Typescript folder In Visual Studio 2019, Extensions > Manage Extensions, install Typescript 4.1 for Visual Studio


R
Raine Revere

Solution for Sublime Text:

Make sure your package.json uses Typescript >= v4.1.2 Uninstall the Sublime Text "Typescript" package through Package Control At time of writing, it bundles Typescript v3.x Open a terminal in the Sublime Text "Packages" directory. cd "~/Library/Application Support/Sublime Text 3/Packages" Clone the Typescript-Sublime-Plugin repo into your Packages directory: git clone https://github.com/microsoft/TypeScript-Sublime-Plugin TypeScript Open User Settings: Sublime Text > Preferences > Settings Add "typescript_tsdk": "node_modules/typescript/lib" This tells the Sublime Typescript plugin to use the project version of Typescript rather than its bundled version. Restart Sublime Text Unlike most Sublime Text settings, this one requires a restart in order to restart the Typescript server.

Reference:
https://github.com/microsoft/TypeScript-Sublime-Plugin/issues/538


This was able to solve a problem I had with React 17 and using the "jsx": "react-jsx" problem.
Quick clarification for Windows 10 users, according to Microsoft's github README.md, step 4 must be run in the %APPDATA%\Sublime Text 3\Packages directory. An easy way to find where yours is is by navigating within Sublime Text 3 to: Preferences->Browse Packages.
A
Amit Chaurasia

This link was helpful to resolve this issue: https://staxmanade.com/2015/08/playing-with-typescript-and-jsx/

Refer the section: Fixing error TS17004: Cannot use JSX unless the '--jsx' flag is provided.

The next error is new to me, but it makes some sense, so I add the --jsx flag to tsc and try tsc --jsx helloWorld.tsx, but looks like I missed a parameter to --jsx.

tsc --jsx helloWorld.tsx message TS6081: Argument for '--jsx' must be 'preserve' or 'react'. In the current iteration of TypeScript 1.6 appears to have two options for --jsx, both preserve or react.

preserve will keep the jsx in the output. I presume this is so you can use tools like JSX to actually provide the translation. react will remove the jsx syntax and turn it in to plain javascript so in the TSX file would become React.createElement("div", null). By passing the react option, here's where we end up:

tsc --jsx react helloWorld.tsx helloWorld.tsx(11,14): error TS2607: JSX element class does not support attributes because it does not have a 'props' property helloWorld.tsx(11,44): error TS2304: Cannot find name 'mountNode'. I'm going to tackle the last error next, as initially I didn't understand the JSX error above.


usually my tsconfig would change on yarn start but it did not this time. adding uncommenting "jsx":"preserve" in tsconfig.json worked for me
R
Rosco

I got this same error, and just figured out how to resolve it. The problem was that there was a jsconfig.json file which caused the TypeScript compiler to ignore the tsconfig.json file.

To determine if you have the same problem, in your IDE (I'm using VS Code), load a file which has the error in your editor, then bring up the Command Palette and enter "TypeScript: Go to Project Configuration". If it opens up jsconfig.json, then delete that file and restart your IDE. If it opens the tsconfig.json file this time, you are golden.


G
Gunther

Restarting my IDE didn't help. Restarting the TypeScript server did resolve it tho.


A
Ace

I just fixed this problem with a bud of mine who was reinstalling and reconfiguring every damn thing to fix it. We tried every fix on the internet (I even had to solve this myself, so I was really confused why we could fix it for him).

The problem turned out to be this TypeScript God extension. Once it was disabled, and subsequently removed, the issue was solved.

Beware the False God!


The link throws 404
@trainoasis It must have been removed.
e
emccracken

I have a monorepo and for me Webstorm automagically had chosen an older version of TypeScript for a sub-package. The fix was clicking on TypeScript X.X.X in the footer and choose Configure TypeScript ... and choose the right package, that worked for me in Webstorm 2021.1


I appreciate that someone went ahead and posted a solution for Intellij
A
ArunaT

Adding { "compilerOptions": { "jsx": "react" } } to 'tsconfig.json' file and restarting the editor resolved the problem.


"restarting" was missing for my setup :)
Q
QuickDanger

In my case, I tried all the tsconfig.json, Project Properties dialog, restarting IDE, checking installed TypeScript version, etc, and it still had this error. Come to find out the dev that made the project added conditional properties to the project file, such that TypeScriptJSXEmit is not defined in all configurations (which confused the Project Properties dialog).

Here's an excerpt from my project file showing the issue:

...
  <PropertyGroup Condition="'$(Configuration)' == 'QA'">
    <TypeScriptTarget>ES5</TypeScriptTarget>
    <TypeScriptJSXEmit>React</TypeScriptJSXEmit>
...

Z
ZF007

The below error I am getting after running yarn start:

> multi-step-form-typescript@0.1.0 start /home/ehsan/Documents/GitHub/multi-step-form-typescript
> react-scripts start

/home/ehsan/Documents/GitHub/multi-step-form-typescript/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js:239
      appTsConfig.compilerOptions[option] = value;
                                          ^

TypeError: Cannot assign to read only property 'jsx' of object '#<Object>'
    at verifyTypeScriptSetup (/home/ehsan/Documents/GitHub/multi-step-form-typescript/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js:239:43)
    at Object.<anonymous> (/home/ehsan/Documents/GitHub/multi-step-form-typescript/node_modules/react-scripts/scripts/start.js:31:1)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! multi-step-form-typescript@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the multi-step-form-typescript@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/ehsan/.npm/_logs/2020-11-22T18_20_20_546Z-debug.log

So what you need to do in order to get rid of this

on your terminal click on the error link

/home/ehsan/Documents/GitHub/multi-step-form-typescript/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js:239 appTsConfig.compilerOptions[option] = value;

and then change the 239 lines to

else if (parsedCompilerOptions[option] !== valueToCheck && option !== "jsx")

Now after changing this goto tsconfig.json

and than replace "jsx": "react-jsx" to "jsx": "react"

now run your project with sudo yarn start

It's work for me, hope this will work for you too :)


k
kecheon

In my case, none of the above did work. My problem was that the location of tsconfig.json was not the project root. So that jest could not read .jsx files. I solved it just symlink tsconfig.json to the project root. There might be better solution. Let me know if you have one.


M
Mayowa Daniel

I followed the "Simpler Solution" mentioned here https://github.com/facebook/create-react-app/issues/10144#issuecomment-733278351

"...update the TS version in package.json to 4.1.2"

and then restarted VS Code.

Simply restarting the TS server with the command palette didn't do it for me.

I didn't need any other steps.


m
mmizutani

In my case, restarting VSCode and upgrading typescript and run-scripts to the matching versions were not enough. Rebuilding after deleting the .eslintcache file finally resolved the error.


R
Raine Revere

I had to add my whole app into include.

So my tsconfig.json looks like this:

{
    "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es6",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "jsx": "react",
    "allowJs": true
  },
  "include": ["./"]
}

A
Abhishek Sah

My Experience

I was converting an existing newly created NextJS App to use TS following the official next guide and when i reached to the part where the pages/_app.tsx needed to be modified.

I followed the VSCode prompt to add --jsx flag, which added the following lines to the next.config.js file:

module.exports = {
  reactStrictMode: all,
};

which resulted in another error:

Failed to load next.config.js, see more info here https://nextjs.org/docs/messages/next-config-error
ReferenceError: all is not defined

Upon removing the lines from the next.config.js file and restarting VSCode and rerunning yarn dev or npm run dev and Voila! It started working!


J
Johannes Ströbele

This is a follow-up fo the answer by @basarat, because he partially solved the issues in my case. The problem I was having was error TS6046: Argument for '--jsx' option must be: 'preserve', 'react-native', 'react'. I solved it as follows:

Restart your IDE Delete your tsconfig.json Re-initialise your tsconfig.json using ```tsc --init````

Maybe step one could be skipped, but I did not investigate this.


B
Basitomania

You can create a .vscode/settings.json file at the root of you project. In it type { "typescript.tsdk": "node_modules\\typescript\\lib" } you're good to go.

The issue is that vscode is using an old Typescript version.

image showing code on vscode


关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now