我正在尝试将React添加到Webpack构建的项目中。
然而,无论我怎么尝试,Webpack都无法读取我的文件中的<>
(JSX)。
ERROR in ./src/index.js 16:4
Module parse failed: Unexpected token (16:4)
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
|
| ReactDOM.render(
> <h1>Hello World</h1>,
| document.getElementById('root')
| );
下面是我的import语句:
import React from 'react';
import ReactDOM from 'react-dom/client';
以下是我的package.json的Webpack相关部分:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/cli": "^7.21.0",
"@babel/core": "^7.21.4",
"@babel/preset-env": "^7.21.4",
"@babel/preset-react": "^7.18.6",
"babel-loader": "^9.1.2",
"css-loader": "^6.7.3",
"style-loader": "^3.3.2",
"webpack": "^5.78.0",
"webpack-cli": "^5.0.1"
},
"dependencies": {
"core-js": "^3.30.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
下面是我的webpack.config.js:
const path = require('path');
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.(?:js|mjs|cjs)$/,
"exclude": [
/node_modules[\\/]core-js/,
/node_modules[\\/]webpack[\\/]buildin/,
],
use: {
loader: 'babel-loader',
options: {
presets: [
['@babel/preset-env', { targets: "defaults" }, '@babel/preset-react']
],
plugins: ['@babel/plugin-proposal-class-properties']
}
}
}
]
},
module: {
parser: {
javascript: {
// ...
commonjsMagicComments: true,
},
},
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
};
最后,这是我的babel.config.json:
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1"
},
"useBuiltIns": "usage",
"corejs": "3.6.5"
}
],
[
"@babel/preset-react",
{
"pragma": "dom", // default pragma is React.createElement (only in classic runtime)
"pragmaFrag": "DomFrag", // default is React.Fragment (only in classic runtime)
"throwIfNamespace": false, // defaults to true
"runtime": "classic" // defaults to classic
// "importSource": "custom-jsx-library" // defaults to react (only in automatic runtime)
}
]
]
}
备注:
- 当我从index.js文件中删除有问题的
<>
时,项目构建时没有任何错误。 - 我查阅了所有这些资源:
- https://webpack.js.org/loaders/babel-loader/#the-nodejs-api-for-babel-has-been-moved-to-babel-core
- https://babeljs.io/docs/babel-preset-react
- https://babeljs.io/setup#installation
- https://react.dev/learn/add-react-to-an-existing-project
- 我已经摆弄了核心js和各种清理
1条答案
按热度按时间nkoocmlb1#
我承认你的问题,我猜。根据我的说法,如果你试图使用webpack和babel手动构建你的react项目,那么你应该安装“HtmlWebpackPlugin”。我在此附上一个示例webpack.config.js代码供你参考:
在这里,我已经在webpack.config.js文件中导入了“HtmlWebpackPlugin”。此外,如果你看到,你应该考虑更改代码行:
如:
现在,为了检测HTML文件,您应该考虑将代码:
因此,您可以考虑在webpack.config.js中插入的最后一个代码块如下所示:
因此,根据我的说法,尝试以指定的方式配置这个webpack.config.js可以帮助您解决错误。