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';
| ^