【发布时间】:2019-04-06 15:28:02
【问题描述】:
我正在尝试使用 webpack、typescript 和 react 建立一个项目。我正在使用 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 不能处理数组声明?这在我看来有点奇怪。也因为我的反应类看起来不同:
app.tsx
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 解决它:
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,
},
},
...
]
}
]
},
...
};
};
package.json
涉及的包列表如下所示:
...
"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"
}
也许你们中的一些人有一个解决方案来解决如何通过适当的配置来防止这个问题。 :)
【问题讨论】:
标签: reactjs typescript webpack babeljs babel-loader