【发布时间】:2020-08-30 10:17:16
【问题描述】:
我正在学习使用webpack开发一个react项目,但是我无法在本地启动本地服务。它报告以下错误。
ERROR in ./src/index.js 5:16
Module parse failed: Unexpected token (5:16)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import App from './App';
|
> ReactDOM.render(<App />, document.getElementById('root'));
|
我怀疑这是babel编译的问题,但是我配置了babel-loader,但是还是不行。这个问题我google了很久,还是没找到问题。你能帮助我吗?谢谢!
这是我的配置文件。
// webpack.common.js
const path = require('path');
const commonConfig = {
entry: [
'babel-polyfill',
'../src/index.js'
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'dist/index.html')
})
],
module: {
rules: [{
test: /\.(jsx?|tsx?)$/,
loader: 'babel-loader',
exclude: /node_modules/,
}]
}
};
module.exports = commonConfig;
// webpack.dev.js
const merge = require('webpack-merge');
const commonConfig = require('./webpack.common.js');
const path = require('path');
const devConfig = merge(commonConfig, {
mode: 'development',
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 3000
}
})
module.exports = devConfig;
// package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server",
},
"devDependencies": {
"@babel/core": "^7.11.4",
"@babel/preset-env": "^7.11.0",
"@babel/preset-react": "^7.10.4",
"babel-core": "^6.26.3",
"babel-loader": "^8.1.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^4.3.0",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1"
// .babelrc
{
"presets": ["env", "react"]
}
【问题讨论】:
-
我猜因为你的文件以
.js结尾,所以它没有被 babel 加载器拾取。由于您正在创建一个 React 应用程序,除非您想深入了解 webpack/babel 的工作原理,否则只需使用 create-react-app。 -
你配置 Babel 来应用 React 预设了吗?
-
但是我的配置是
test: /\.(jsx?|tsx?)$/,我觉得.js文件也可以。@ChrisG -
我在
. babelrc文件中配置了{ "presets": ["env", "react"] }。 @jonrsharpe -
你似乎在混合 Babel 6 和 7,你能进一步简化这个例子吗?
标签: javascript reactjs webpack webpack-dev-server