【发布时间】:2015-11-23 22:15:20
【问题描述】:
我正在尝试使用 Webpack 转译一些使用 ES6 语法和 JSX 编写的源文件。但是,当我运行 Webpack 命令时,出现以下错误。
ERROR in ./app/App.jsx
Module parse failed: ./app/App.jsx Line 5: Unexpected token
You may need an appropriate loader to handle this file type.
| 'use strict';
|
| import React from 'react';
| import { RouteHandler } from 'react-router';
|
@ multi main
正如您将在下面看到的,我正在使用 babel-loader,但在我看来,加载器无法处理“导入”语法。知道为什么会发生这种情况吗?
这是我们的基本文件结构。
--/app
----/components
------/shared
--------NavigationBar.js
----App.jsx
--webpack.config.js
--package.json
这是我们的 package.json 文件。
// package.json
{
"scripts": {
"start": "webpack-dev-server --hot --inline",
},
"devDependencies": {
"babel-core": "^6.2.1",
"babel-loader": "^6.2.0",
"react-hot-loader": "^1.3.0",
"webpack": "^1.12.6",
"webpack-dev-server": "^1.12.1"
},
"dependencies": {
"history": "^1.13.1",
"react": "^0.14.3",
"react-dom": "^0.14.3",
"react-router": "^1.0.0"
}
}
这是我们的 webpack.config.js 文件。
// webpack.config.js
module.exports = {
context: __dirname + '/app',
entry: './App.jsx',
output: {
filename: 'app.js',
path: __dirname + '/dist',
},
module: {
loaders: [
{
test: /\.js?$/,
loaders: ['react-hot', 'babel'],
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
};
最后,这里是 /app/App.jsx
// App.jsx
'use strict';
import React from 'react';
import { RouteHandler } from 'react-router';
import NavigationBar from './components/shared/NavigationBar';
class App extends React.Component {
render() {
return (
<div>
<NavigationBar />
<RouteHandler />
</div>
);
}
}
export default App;
如果您需要更多信息来诊断问题,请告诉我。提前感谢您的帮助。
【问题讨论】:
-
这个问题几乎每天都会被问到。使用搜索或浏览 babeljs 标签,您应该不难找到相关信息。
-
@FelixKling 我实际上已经尝试过这个解决方案,但它并没有解决问题。由于指定预设后问题仍未解决,因此我将其删除。在对 webpack 配置文件中的代码进行了更深入的视觉检查之后,我还发现我在文件扩展名的正则表达式测试中有一个错字。你看,我的入口点是 app/App.jsx,但正则表达式测试
/\.js?$/与 .jsx 扩展名不匹配。所以我的入口点没有被编译。修复后,我发现缺少的预设也是一个问题。不过谢谢大家的帮助。
标签: ecmascript-6 webpack babeljs