How can webpack and babel be configured to manage TypeScript's private keyword?

I am currently using webpack and babel to compile typescript, but I have encountered an issue with the private keyword in Typescript. While they are working fine with compiling files in general, they do not seem to properly handle the private keyword. I have tried looking for solutions online but have not been successful so far.

Does anyone know how to configure webpack and babel to properly recognize Typescript's private keyword?

.babelrc:

{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-typescript",
        "@babel/preset-react"
    ],
    "plugins": [
        "@babel/plugin-transform-typescript",
        "@babel/proposal-class-properties",
        "@babel/proposal-object-rest-spread"
    ]
}

webpack.config.js: ...

{
            test: /\.(ts|js)x?$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
            },
        },

EDIT: In response to a request for reproduction details, this seems like a common issue that can be reproduced based on the provided information. The problem stems from babel-loader's limited support for Typescript. Simply create a class and include a private field as shown in the following example: private whatever: string. This should trigger an "unrecognized token" error with the current configuration.

EDIT 2: package.json has been included as requested:

{
  "name": "blah",
  "version": "1.0.0",
  "description": "blah config",
  "main": "index.js",
  "scripts": {
    "bundle": "webpack",
    "start": "webpack-dev-server --config ./webpack.config.js --mode development",
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode production",
    "check-types": "tsc"
  },
  "devDependencies": {
    "@babel/core": "^7.11.1",
    "@babel/plugin-proposal-class-properties": "^7.10.4",
    "@babel/plugin-proposal-object-rest-spread": "^7.11.0",
    "@babel/preset-env": "^7.11.0",
    "@babel/preset-react": "^7.10.4",
    "@babel/preset-typescript": "^7.10.4",
    "babel-loader": "^8.1.0",
    "css-loader": "^4.2.1",
    "html-webpack-plugin": "^4.3.0",
    "style-loader": "^1.2.1",
    "tslint": "^6.1.3",
    "tslint-immutable": "^6.0.1",
    "typescript": "^3.9.7",
    "webpack": "^4.44.1",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  },
  "dependencies": {
    "@types/react": "^16.9.46",
    "@types/react-dom": "^16.9.8",
    "react": "^16.13.1",
    "react-dom": "^16.13.1"
  }
}

Example of failure:

class Example {
 private anyField = 'danger';
}

Example of error message:

SyntaxError [path] Unexpected token (2:12)
  1 | class Example {
> 2 |     private anyField = 'danger';
    |             ^

Answer №1

If you're looking to enhance your Vue project with TypeScript, consider using babel-preset-typescript-vue

  • Check out version 1.1.1 for optimal compatibility with [email protected]
  • Prefer version 1.1.0 for Vue versions prior to 2.7

Answer №2

Shifting the file to a different directory seemed to have an unexpected effect on its compilation process. The reason behind this impact is still unclear to me. The specific file in question was located two levels below the main webpack configuration, causing it to behave differently than files situated above that configuration.

It's possible that the lower directory levels were mistakenly interpreted as traditional javascript despite having the appropriate file extension.

In theory, the most recent versions of babel/webpack should support Typescript compilation with both the private and readonly keywords. However, there have been issues in the past where these keywords caused problems in babel. If you encounter similar difficulties, consider experimenting with the file structure. It's intriguing how the directory level plays a role in compilation even when the configuration files are set up correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Module TypeScript could not be located

Currently, I am in the process of converting my nodejs project from JavaScript to TypeScript. I have updated the file extensions from .js to .ts, but now I am encountering errors with require(). In an attempt to fix this issue, I have added the following c ...

Position components in Angular 2 based on an array's values

Hello all, I am a beginner in terms of Angular 2 and currently facing some obstacles. My goal is to create a board for a board game called Reversi, which has a similar layout to chess but with mono-color pieces. In order to store the necessary information, ...

Utilizing Angular 4: Sharing Data through Services and Components

After transitioning my data from an object in a service to a database connection, I'm facing issues where the data is not reaching the component as expected. To solve this problem, I have set up the service to subscribe to the data retrieved from the ...

Error in Typescript compiler occurs when comparing mutable enum member variables

Encountering the following error message: TS2365: Operator '===' cannot be applied to types 'ExampleState.Unsaved' and 'ExampleState.Saving'. While trying to compare an enum with a mutable member variable: enum ExampleState ...

One way to update the value of the current array or object using ngModel in Angular 2 is to directly

I have a situation where I am dealing with both an array and an object. The array is populated with data retrieved from a service, while the object contains the first element of that array. feesEntries: Array<any> = []; selectedFeesEntry: any; clien ...

The traditional Angular model definition has been revamped with the implementation of web services model

I have a TypeScript model that looks like this: import * as moment from 'moment'; export class Activity { public id: number; public activityDate: string; public day: number = moment(this.activityDate).dayOfYear(); } Also, a C ...

Creating a new array for an Angular 5 class instance

My goal is to create and initialize an array of a class in Angular 5. export class B{ public Colors: string; public Temp: number; public Numbers: number; } export class A{ public MyTable: B[]; public othervar: number; ... ... } Next, I ...

Oops! Looks like there was an issue with assigning to a reference or variable: Error: Uncaught (in promise)

I seem to be struggling with an issue that I believe may have been addressed before, but after reviewing other solutions, I am unable to pinpoint the error in my code. Any assistance in identifying my mistake would be greatly appreciated. <div class="j ...

Necessary Typescript class property when executing code

Is there a way to determine if a class property is required in Typescript at runtime? export class A { public readonly ab?: number; public readonly ac?: number; public readonly ad: number; public readonly ae: number; } Can emitDecoratorMetadata o ...

Out of the blue, I encountered an issue while trying to install Express in node.js using Types

Encountered a failure while attempting to install Express with node.js in Typescript. Received the following warning: https://i.sstatic.net/XcrGX.png Performed npm initialization, started index.js, created tsconfig.json, and installed ts-node. The comman ...

Send the Children prop to the React Memo component

Currently, I am in the stage of enhancing a set of React SFC components by utilizing React.memo. The majority of these components have children and the project incorporates TypeScript. I had a notion that memo components do not support children when I en ...

Raycast failing to detect objects that have been displaced from their original starting position

I am facing a challenge with using a raycast to locate objects under the mouse cursor. The issue arises when the objects are not positioned at (0, 0, 0) as they cannot be detected by the raycast. Once I move the object to any other position, it no longer r ...

Angular Reactive Forms provide a powerful tool for handling complex data structures,

I have encountered an issue with creating and editing volumes using Angular. I am utilizing reactive forms, but struggling to display volume authors when attempting to edit them. While the authors are dynamically generated during volume creation, they do ...

Using TypeScript Generics to Automatically Infer Types Based on Field Values

enum Letter { A = "A", B = "B", C = "C" } export type EntityT<T extends Letter = Letter> = T extends Letter.A ? { a: number } : T extends Letter.B ? { b: string } : T extends Letter.C ? { c: string } : ...

"Using RxJS to create an observable that filters and splits a string using

I need to break down a string using commas as separators into an observable for an autocomplete feature. The string looks something like this: nom_commune = Ambarès,ambares,Ambares,ambarès My goal is to extract the first value from the string: Ambarès ...

Learn the technique of passing dual onClick parameters to a single function in React

I am working on a function named Test where I need to pass two onClick references. const Test = ({ onConnect }:{ onConnect:any }, { onDisconnect }:{ onDisconnect:any }) => { return ( <div> <DrawDiagram /> <button onClick ...

Set up a new React 18 project with TypeScript using Create React App

Struggling with creating a React 18 app using TypeScript, I attempted to follow this guide but faced difficulties. Adding "types": ["react/next", "react-dom/next"] to the tsconfig file is giving me errors: Cannot find type def ...

Fixing Email Validation Error in AngularLearn how to troubleshoot and resolve

I'm encountering an issue when trying to develop an email center using regex pattern, as I'm receiving a validator error in HTML. I have already installed ngx-chips and angular-editor, imported all the necessary modules and dependencies. Here is ...

Tips for customizing Material UI CSS default properties in React

I'm currently working on a React project and utilizing the 'Table' component from Material UI. The default CSS properties of this table, along with its components like TableHead, TableCell, and TableRow, are proving difficult to override whi ...

Fails to update the ngModel linked to the checkbox

<label class="checkiconImg bg-white"> <input type="checkbox" [(ngModel)]="quoteSupplierCover.isShowInComparisonTool" /> <span class="geekmark ShowInComparisonToolCheckBox" ...