我正在尝试使用webpack,打字稿和反应来建立一个项目。我正在使用babel来翻译我的打字稿/反应代码。在启动开发服务器时,我得到以下错误:
Module parse failed: Unexpected token (4:6)
You may need an appropriate loader to handle this file type.
|
| export class App extends React.Component {
> arr = [1, 2, 3];
|
| render() {
Babel无法处理数组声明?在我看来,这有点奇怪。也是因为我的react类看起来不同:
export class App extends React.Component {
public arr: number[] = [1, 2, 3];
public render(): React.ReactNode {
...
}
}
export default App;
我现在尝试阻止.babelrc
或babel.config.js
文件,并尝试通过我的webpack.config.js
解决该文件:
出于澄清的原因,我删除了大多数不必要的配置:
module.exports = (env) => {
const isProduction = env.production === true;
const isDevelopment = env.development === true;
return {
entry: {
main: srcDir + '/index.tsx'
},
...
module: {
rules: [
{
oneOf: [
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: srcDir,
loader: 'babel-loader',
options: {
babelrc: false,
configFile: false,
presets: [
["@babel/preset-react"],
["@babel/preset-typescript"]
],
plugins: [
[
'babel-plugin-named-asset-import',
{
loaderMap: {
svg: {
ReactComponent: '@svgr/webpack?-svgo,+ref![path]',
},
},
},
],
],
cacheDirectory: true,
cacheCompression: isProduction,
compact: isProduction,
},
},
...
]
}
]
},
...
};
};
涉及的软件包清单如下:
...
"devDependencies": {
"@babel/core": "^7.4.0",
"@svgr/webpack": "^4.1.0",
"babel-loader": "^8.0.5",
"babel-plugin-named-asset-import": "^0.3.1",
"@babel/preset-react": "^7.0.0",
"@babel/preset-typescript": "^7.3.3",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0"
},
"dependencies": {
"@types/react": "^16.8.12",
"@types/react-dom": "^16.8.3",
"@types/react-router-dom": "^4.3.1",
"react": "^16.8.6",
"react-dom": "^16.8.6"
}
也许你们中的一些人有一个适当的配置来防止此问题的解决方案。 :)
答案 0 :(得分:1)
看起来它与打字稿无关或没有响应解析,我相信您缺少以下Babel插件:https://babeljs.io/docs/en/babel-plugin-proposal-class-properties
此插件允许Babel正确解析类属性(如数组)。
要安装
npm install --save-dev @babel/plugin-proposal-class-properties
,然后将其添加到插件列表中的babel loader配置中。
plugins: [
"@babel/plugin-proposal-class-properties",
[
'babel-plugin-named-asset-import',
{
loaderMap: {
svg: {
ReactComponent: '@svgr/webpack?-svgo,+ref![path]',
},
},
},
],
]