gpt4 book ai didi

typescript - 如何让 webpack 和 babel 处理 private typescript 关键字?

转载 作者:行者123 更新时间:2023-12-05 08:05:49 31 4
gpt4 key购买 nike

我有 webpack 和 babel 编译 typescript ,但他们似乎不知道如何处理 typescript 中的 private 关键字。一般来说,他们似乎对 Typescript 没有问题,我可以编译文件。所以我想知道我是否需要做一些配置更改,但谷歌搜索没有帮助。

如何让 webpack 和 babel 与 Typescript 的私有(private)关键字配合使用?

.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',
},
},

编辑:有人要求提供复制细节,我认为用我提供的内容很容易复制这个。以前看过,跟babel-loader对typescript的准支持有关。创建一个类并为其添加一个私有(private)字段。 私有(private)的:字符串。这应该足以使 unrecognized token 错误出现在我提供的配置中。

编辑 2:package.json 根据要求:

{
"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"
}
}

失败示例:

class Example {
private anyField = 'danger';
}

错误信息示例:

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

最佳答案

也许你需要babel-preset-typescript-vue

  • Vue@2.7 版本 1.1.1
  • Vue@<2.7 版本 1.1.0

关于typescript - 如何让 webpack 和 babel 处理 private typescript 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63441681/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com