question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Typescript declare field causes transpile to fail

See original GitHub issue

Describe the bug

Using typescript declare to fix the type of the context field in class components causes the build to fail with

./src/App.tsx
SyntaxError: C:\Users\wiles\Documents\git\broken-cra\src\App.tsx: TypeScript 'declare' fields must first be transformed by @babel/plugin-transform-typescript.
If you have already enabled that plugin (or '@babel/preset-typescript'), make sure that it runs before any plugin related to additional class features:
 - @babel/plugin-proposal-class-properties
 - @babel/plugin-proposal-private-methods
 - @babel/plugin-proposal-decorators
  10 | class MyComponent extends React.Component {
  11 |   static contextType = MyContext;
> 12 |   declare context: React.ContextType<typeof MyContext>;
     |   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  13 | 
  14 |   render() {
  15 |     return <span>{this.context.data || "No context"}</span>;

Did you try recovering your dependencies?

Yes

npm --version
6.14.4

Which terms did you search for in User Guide?

typescript declare transpile

Environment

npx create-react-app --info
npx: installed 98 in 23.993s

Environment Info:

  current version of create-react-app: 3.4.1
  running from C:\Users\wiles\AppData\Roaming\npm-cache\_npx\2632\node_modules\create-react-app

  System:
    OS: Windows 7 6.1.7601
    CPU: (8) x64 Intel(R) Core(TM) i7-2820QM CPU @ 2.30GHz
  Binaries:
    Node: 12.16.1 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.4 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 6.14.4 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Internet Explorer: 11.0.9600.18123
  npmPackages:
    react: ^16.13.1 => 16.13.1
    react-dom: ^16.13.1 => 16.13.1
    react-scripts: 3.4.1 => 3.4.1
  npmGlobalPackages:
    create-react-app: Not Found

Steps to reproduce

  1. Add the following component to a React hierarchy
interface MyContextValue {
  data?: string;
}
const MyContext = React.createContext<MyContextValue>({});

class MyComponent extends React.Component {
  static contextType = MyContext;
  declare context: React.ContextType<typeof MyContext>;

  render() {
    return <span>{this.context.data || "No context"}</span>;
  }
}
  1. Try to build the app with npm start or npm run build

Expected behavior

That the build will succeed

Actual behavior

Build fails with

./src/App.tsx
SyntaxError: C:\Users\wiles\Documents\git\broken-cra\src\App.tsx: TypeScript 'declare' fields must first be transformed by @babel/plugin-transform-typescript.
If you have already enabled that plugin (or '@babel/preset-typescript'), make sure that it runs before any plugin related to additional class features:
 - @babel/plugin-proposal-class-properties
 - @babel/plugin-proposal-private-methods
 - @babel/plugin-proposal-decorators
  10 | class MyComponent extends React.Component {
  11 |   static contextType = MyContext;
> 12 |   declare context: React.ContextType<typeof MyContext>;
     |   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  13 | 
  14 |   render() {
  15 |     return <span>{this.context.data || "No context"}</span>;

Reproducible demo

https://github.com/benwiles1/broken-cra

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:23
  • Comments:18

github_iconTop GitHub Comments

5reactions
dongjinccommented, May 14, 2021

I also meet this question,It’s via babel plugins add -> @babel/plugin-transform-typescript and options -> “allowDeclareFields”: true the following my .babelrc file

{
 "presets": [
    "react-app"
  ],
  "plugins": [
    [
      "@babel/plugin-transform-typescript",
      {
        "allowDeclareFields": true
      }
    ]
  ]
}

will need -> yarn add @babel/plugin-transform-typescript -D

2reactions
itsjohncscommented, Apr 30, 2022

You can work around this using CRACO. I’ll share my configuration, but first a warning: I barely understand web pack’s configuration and figured this out through trial and error. Be wary.

// craco.config.js

const {
    loaderByName,
    getLoader,
} = require("@craco/craco");

module.exports = {
    webpack: {
        configure: function (webpackConfig) {
            const babelLoader = getLoader(
                webpackConfig,
                loaderByName("babel-loader")
            ).match.loader;
            babelLoader.options.presets.push([
                "@babel/preset-typescript",
                {allowDeclareFields: true},
            ]);

            return webpackConfig;
        }
    }
};
Read more comments on GitHub >

github_iconTop Results From Across the Web

Typescript fails to transpile when leaving out spread of ...
When I run tsc the transpilation fails with an error that refer to files that import this config.js file. The error seems to...
Read more >
Documentation - TypeScript 2.0
A property access or a function call produces a compile-time error if the object or function is of a type that includes null...
Read more >
Documentation - TypeScript 3.7
While not a breakage per se, opting in to the useDefineForClassFields flag can cause breakage when: overriding an accessor in a derived class...
Read more >
TSConfig Reference - Docs on every TSConfig option
When set to true, TypeScript will raise an error when a class property was declared but not set in the constructor. ts. class...
Read more >
Documentation - TypeScript 3.8
This can cause imports/side-effects to be preserved. error : this ... (even ones declared with the private modifier), private fields have a few...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found