Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot compile TypeScript app created with CRA because of parsing errors #9791

Open
tx46 opened this issue Oct 13, 2020 · 25 comments
Open

Cannot compile TypeScript app created with CRA because of parsing errors #9791

tx46 opened this issue Oct 13, 2020 · 25 comments

Comments

@tx46
Copy link

tx46 commented Oct 13, 2020

Describe the bug

create-react-app seems to have issues compiling valid TypeScript code.

Did you try recovering your dependencies?

Yes, in a number of ways. I cannot manage to fix this, despite spending hours on researching it.

I've tried:

  1. Googling (finding semi-similar issues reported, but no answers or solutions)
  2. Removing node_modules and doing npm install and npm ci
  3. Removing package-lock.json and npm install and npm ci
  4. Reconstructing the entire package.json file by doing npm install <package-name> for every single dependency.

Which terms did you search for in User Guide?

parsing error, unexpected token, syntax error, create-react-app, private access modifier, failed to compile, typescript syntax error and tons of permutations of these.

Environment

  • Windows 10 x64
  • node v12.19.0
  • npm 6.14.8

Steps to reproduce

  1. npx create-react-app my-app --typescript
  2. Edit App.tsx and add the following code under the import statements and above the function App() ... line:
class Foo {
  private bar: number;

  constructor() {
    this.bar = 1;
  }
}

Full content of App.tsx:

import React from 'react';
import logo from './logo.svg';
import './App.css';

class Foo {
  private bar: number;

  constructor() {
    this.bar = 1;
  }
}

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;
  1. Run npm run build

NOTE: There are other syntaxes which do not work, such as readonly and more.

Expected behavior

The app is compiled successfully.

Actual behavior

λ npm run build

> [email protected] build C:\Users\...\my-app
> react-scripts build

Creating an optimized production build...
Failed to compile.

C:/Users/.../my-app/src/App.tsx
  Line 6:11:  Parsing error: Unexpected token

  4 |
  5 | class Foo {
> 6 |   private bar: number;
    |           ^
  7 |
  8 |   constructor() {
  9 |     this.bar = 1;


npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `react-scripts build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build 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!     C:\Users\...\npm-cache\_logs\2020-10-13T05_11_20_782Z-debug.log
@tx46
Copy link
Author

tx46 commented Oct 13, 2020

Interestingly, I just tried this on Ubuntu 18.04 with the exact same node/npm versions. It's compiling there:

Creating an optimized production build...
Compiled with warnings.

./src/App.tsx
  Line 5:7:  'Foo' is defined but never used  @typescript-eslint/no-unused-vars

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

File sizes after gzip:

  39.44 KB (+50 B)  build/static/js/2.983335a4.chunk.js
  772 B             build/static/js/runtime-main.83c3e0c4.js
  649 B (+2 B)      build/static/js/main.1b78e738.chunk.js
  547 B             build/static/css/main.5f361e03.chunk.css

I also just tried it on another (complete fresh) install of Windows 10 x64 on another computer (with node 12.16.3 and npm 6.14.4). That machine fails exactly like in the bug report above.

Please help - we're unable to build or product on any new Windows machines right now!

@tx46
Copy link
Author

tx46 commented Oct 14, 2020

This is no longer reproducible (but still occurs in another project of ours), so something bad had been published. Unsure how to fix in other project. npm upgrade dit not solve the issue.

@pluma
Copy link

pluma commented Oct 26, 2020

I'm having the same problem and have been having it since once of the pre-releases. I've gathered that it may be an issue with typescript-eslint but it's making me pull my hair out because CRA doesn't tell me what exactly fails (i.e. no stack trace or even "this is eslint complaining") other than pointing out those nonsense parsing errors on almost every TS and TSX file. I suspect this may have something to do with this being in a monorepo.

@pluma
Copy link

pluma commented Oct 26, 2020

Okay, scratch that. After comparing the output of a fresh yarn create react-app with my existing package.json it seems that the file now contains the following section:

  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },

This was missing in the app I upgraded. Presumably this was added to the generator output at some point in the past but inferred if missing and that logic got canned at some point in the 4.0.0 pre-releases, breaking old apps that were missing this bit.

Adding this to my package.json fixed the problem, monorepo or not.

@szmarci
Copy link

szmarci commented Oct 26, 2020

@pluma Thank god! I was dealing with this all day... I even tried to migrate to snowpack, but that is even more pain...
Thanks again.

@tx46
Copy link
Author

tx46 commented Oct 30, 2020

Okay, scratch that. After comparing the output of a fresh yarn create react-app with my existing package.json it seems that the file now contains the following section:

  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },

This was missing in the app I upgraded. Presumably this was added to the generator output at some point in the past but inferred if missing and that logic got canned at some point in the 4.0.0 pre-releases, breaking old apps that were missing this bit.

Adding this to my package.json fixed the problem, monorepo or not.

This doesn't work for me.

I already had this in my package.json file:

  "eslintConfig": {
    "extends": "react-app"
  },

I changed it to this:

  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },

I'm still having the same problem -- the project still fails to build on syntax like private or readonly. I can only build the project on Linux machines right now (or with WSL). Neither deleting the packag-lock.json file and doing npm install nor doing npm ci works.

@roygiladi
Copy link

Not sure why yet, but the thing that has solved this problem for me was deleting an .eslintrc file I had in the root folder

@tx46
Copy link
Author

tx46 commented Nov 2, 2020

Not sure why yet, but the thing that has solved this problem for me was deleting an .eslintrc file I had in the root folder

Thanks. Doesn't work for me - I don't even have that file.

@unframework
Copy link

unframework commented Nov 3, 2020

I did some digging and it seems like this was introduced by the changes to ESLint config handling in v4.0 (see https://github.com/facebook/create-react-app/pull/9587/files#diff-8e25c4f6f592c1fcfc38f0d43d62cbd68399f44f494c1b60f0cf9ccd7344d697L372 and then https://github.com/facebook/create-react-app/pull/9640/files#diff-8e25c4f6f592c1fcfc38f0d43d62cbd68399f44f494c1b60f0cf9ccd7344d697R366).

In particular, the default lint config is now using eslint-config-react-app/base instead of eslint-config-react-app/index: this matters because only the latter configures a TS-aware lint parser.

Likely solution is to move TS-aware parser config to the base file?

@tx46
Copy link
Author

tx46 commented Nov 3, 2020

I did some digging and it seems like this was introduced by the changes to ESLint config handling in v4.0 (see https://github.com/facebook/create-react-app/pull/9587/files#diff-8e25c4f6f592c1fcfc38f0d43d62cbd68399f44f494c1b60f0cf9ccd7344d697L372 and then https://github.com/facebook/create-react-app/pull/9640/files#diff-8e25c4f6f592c1fcfc38f0d43d62cbd68399f44f494c1b60f0cf9ccd7344d697R366).

In particular, the default lint config is now using eslint-config-react-app/base instead of eslint-config-react-app/index: this matters because only the latter configures a TS-aware lint parser.

Likely solution is to move TS-aware parser config to the base file?

Thanks. Unsure how to test your solution - could you provide a short step-by-step? I'll test it out because I still can't build the project on Windows.

@unframework
Copy link

Sorry @philiparvidsson, I meant that as a suggestion for a general fix in the CRA source code.

In your particular situation it does sound like there is something interfering with your lint config, maybe there is a way to get eslint to dump configuration for further debugging? The workarounds from other commenters worked ok for me.

@tx46
Copy link
Author

tx46 commented Nov 3, 2020

Sorry @philiparvidsson, I meant that as a suggestion for a general fix in the CRA source code.

In your particular situation it does sound like there is something interfering with your lint config, maybe there is a way to get eslint to dump configuration for further debugging? The workarounds from other commenters worked ok for me.

Thanks. Yes, something is indeed interfering. The project was untouched but just stopped building after a while (after removing node_modules and doing npm install), and I haven't been able to build it on Windows since.

@stale
Copy link

stale bot commented Dec 25, 2020

This issue has been automatically marked as stale because it has not had any recent activity. It will be closed in 5 days if no further activity occurs.

@stale stale bot added the stale label Dec 25, 2020
@yoruvo
Copy link

yoruvo commented Jan 28, 2021

Hi @philiparvidsson, I have just suddenly begun receiving the exact same error out of nowhere, for no reason. Also running Windows. It just broke from one moment to the next.

Failed to compile.

../shared/src/lib/Sanity.ts 4:30
Module parse failed: Unexpected token (4:30)
File was processed with these loaders:

  • ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
    You may need an additional loader to handle the result of these loaders.
    | $RefreshSetup$(module.id);

|

export const objectHasProps = <T extends Record<string, unknown>>(
| x: Partial,
| props: Extract<keyof T, string>[],

The problem is that "4:30" literally does not exist. There is no line 4 which has 30 positions, and the pinpointed code snippet is actually line 1. And it is completely harmless, regular code, which has worked the entire time. Position 30 is a space.

If I add a comment in the file, the error jumps to another file. If I keep adding comments, eventually it comes back to /Sanity.ts, but 5:30 instead of 4:30.

Have you been able to fix the problem for yourself?

@tx46
Copy link
Author

tx46 commented Jan 29, 2021

Hi @philiparvidsson, I have just suddenly begun receiving the exact same error out of nowhere, for no reason. Also running Windows. It just broke from one moment to the next.

Failed to compile.
../shared/src/lib/Sanity.ts 4:30
Module parse failed: Unexpected token (4:30)
File was processed with these loaders:

  • ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
    You may need an additional loader to handle the result of these loaders.
    | $RefreshSetup$(module.id);

|

export const objectHasProps = <T extends Record<string, unknown>>(
| x: Partial,
| props: Extract<keyof T, string>[],

The problem is that "4:30" literally does not exist. There is no line 4 which has 30 positions, and the pinpointed code snippet is actually line 1. And it is completely harmless, regular code, which has worked the entire time. Position 30 is a space.

If I add a comment in the file, the error jumps to another file. If I keep adding comments, eventually it comes back to /Sanity.ts, but 5:30 instead of 4:30.

Have you been able to fix the problem for yourself?

In the line you pasted (export const...) column 30 is the < character, which is in line with what this bug is describing. Basically it seems to be a lint configuration error that causes anything other than plain-old JavaScript to give syntax errors.

I haven't built the project in a long time on Windows (our build system is Linux and it's working there). Just to give you an answer, I pulled everything to yet another Windows machine (pretty clean install) and ran the CI build script which works on Linux (basically all it does is npm ci and react-scripts build).

Just to inform you: It's still broken. Just before I reported this bug, I could build fine on Windows. But since the report, the build is entirely broken on Windows. We've tried recreating the project, recreating package.json (by manually reinstalling every package with npm i ..., deleting package-lock.json, etc. but nothing fixes it.

So no, I'm not able to fix it. The best suggestion I can give you is to run your builds in Docker, WSL or on a Linux-machine.

@stale stale bot removed the stale label Jan 29, 2021
@yoruvo
Copy link

yoruvo commented Jan 29, 2021

To give an update on my comment yesterday, I was able to resolve my personal problem, which probably ended up unrelated to this topic after all.

My issue was that my project is split into different modules - "client", "shared" and "server", and I was including the "shared" module in my "client" without transpiling the TS first. (Via npm link or npm install ../local/path/to/the/module)

The baffling part is that I have been using the shared package for weeks without the error appearing, and then it suddenly popped up out of nowhere.

The correct solution is probably to just transpile the shared package before using it, but what I did instead was to install CRACO and change the CRA webpack config to add an additional rule:

npm install -D @craco/craco ts-loader

craco.config.js:

const path = require("path");

module.exports = {
  webpack: {
    configure: webpackConfig => {

      // ts-loader is required to reference external typescript projects/files (non-transpiled)
      webpackConfig.module.rules.push({
        test: /\.ts(x)?$/,
        loader: 'ts-loader',
        include: [
          path.resolve(__dirname, '../your/local/path'),
          path.resolve(__dirname, '/node_modules/your-local-package-name'),
        ],
        options: {
          transpileOnly: true,
          configFile: 'tsconfig.json',
        },
      })

      return webpackConfig;
    }
  }
};

and then replace react-scripts start calls in the package.json scripts segment with craco start (and same for build). That resolved my problem.

The problem also happened in WSL2, which tipped me off to the thought that it might not be Windows-related after all.

While my woes ended up not directly related, I hope that the context may provide some ideas for solving this particular case.

@HHK1
Copy link

HHK1 commented Feb 2, 2021

Something I don't understand is why would react-scripts build fail ts compilation because of an incorrect eslint config. I ran into the issue and had difficulties understanding that this was an issue coming from a missing eslint config.
I was building inside a Docker image, where I had not copied my .eslintrc.json, it was hard to troubleshoot.

@harryjubb
Copy link

harryjubb commented Feb 6, 2021

My issue was that my project is split into different modules - "client", "shared" and "server", and I was including the "shared" module in my "client" without transpiling the TS first. (Via npm link or npm install ../local/path/to/the/module)

@yoruvo Thanks for this, helped diagnose something similar happening for me.

I've had this issue with a .ts file soft-symlinked in from outside of the CRA created folders.

Any time it hits TS syntax in that file, I get the same error:

Module parse failed: Unexpected token (<line:char numbers>)
File was processed with these loaders:

./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
You may need an additional loader to handle the result of these loaders.

If I copy the code into a "proper" file in the same place, it works without issue. It also works if there's no Typescript-specific syntax in the file.

With the symlink it seems to be skipping TS transpilation entirely.

From digging a bit deeper it looks like my issue (and maybe yours?) is more #3547

@FranckMuller
Copy link

deleting the eslintrc file helped me

@imransilvake
Copy link

imransilvake commented Mar 11, 2021

Okay, scratch that. After comparing the output of a fresh yarn create react-app with my existing package.json it seems that the file now contains the following section:

  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },

This was missing in the app I upgraded. Presumably this was added to the generator output at some point in the past but inferred if missing and that logic got canned at some point in the 4.0.0 pre-releases, breaking old apps that were missing this bit.

Adding this to my package.json fixed the problem, monorepo or not.

This fixed for me as well. I just saw that this code is in basic CRA too. I might have deleted it at some point.
P.S: my .eslintrc.json file was at the root (outside of the client folder).

@tetchel
Copy link

tetchel commented Mar 22, 2021

for me, react-scripts build was succeeding locally but failing in a docker container. The solution was to copy my .eslintrc.js into the container before doing the build.

My eslintrc does not use react-app or react-app/jest, so it does not seem to be those configs specifically that prevent this issue.

I do not have an eslintConfig section in my package.json.

Bizarre issue.

mimecuvalo added a commit to mimecuvalo/cra-all-the-things that referenced this issue Apr 23, 2021
I came across this when trying to upgrade my company's create-react-app from v3→v4. The migration path doesn't note that you will lose ESLint capabilities unless you specify `eslintConfig` explicitly in your `package.json` going forward.

Progression of ESLint changes in Webpack:
- removal of original extend and addition to `template.json`: https://github.com/facebook/create-react-app/pull/9587/files
- referencing of /base instead of /index: https://github.com/facebook/create-react-app/pull/9640/files#diff-8e25c4f6f592c1fcfc38f0d43d62cbd68399f44f494c1b60f0cf9ccd7344d697R366

This was also noticed by other developers in these bugs:
facebook#9791
facebook#10212
@mpiorowski
Copy link

I have the same situation as @tetchel . I have a client (cra) and server (fastify) setup, and its much better to have one eslint config, kept in the root folder of both apps. So i deleted esling from client package. And now when i put my client part into docker, without eslint config, it cannot compile ts. WHY? :D

@falsyvalues
Copy link

falsyvalues commented Jul 21, 2021

for me, react-scripts build was succeeding locally but failing in a docker container. The solution was to copy my .eslintrc.js into the container before doing the build.

My eslintrc does not use react-app or react-app/jest, so it does not seem to be those configs specifically that prevent this issue.

I do not have an eslintConfig section in my package.json.

Bizarre issue.

Oh god, I had the same issue, another gotcha is .prettierrc.js and others if eslint use them.

@LinusU
Copy link

LinusU commented Nov 4, 2021

For anyone else landing here, and not thinking that linting has anything to do with the error you are having. I just found out that CRA always adds ESLint so it will run even if you remove all your ESLint config. And then it will crash because ESLint without config cannot handle TypeScript.

The fix is to add back:

  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  }

to your package.json

@stale
Copy link

stale bot commented Jan 9, 2022

This issue has been automatically marked as stale because it has not had any recent activity. It will be closed in 5 days if no further activity occurs.

@stale stale bot added the stale label Jan 9, 2022
@stale stale bot removed the stale label Mar 1, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests