【发布时间】:2021-04-14 21:35:55
【问题描述】:
我对 React 很陌生,我的项目遇到了一些问题。我觉得我快疯了,最简单的事情并没有像我期望的那样工作。在这一点上重新阅读我的代码感觉像是数百次,我仍然无法弄清楚我的生活是什么问题。具体来说,我正在测试一个带有 onClick 功能的简单按钮(onClick={() => console.log("test")})。该按钮呈现良好,但单击它不会在控制台中记录任何内容。
我也在使用 Webpack 和 Express(尽管我怀疑 Express 在这一点上会导致任何问题)。
我尝试搜索类似的问题,但到目前为止没有任何帮助。
下面是我的 index.jsx:
import React from 'react';
import ReactDOM from 'react-dom';
import styles from './index.module.scss';
function App() {
return (
<>
<button onClick={() => console.log("Working")} >Test</button>
</>
)
}
ReactDOM.render((
<App />
), document.getElementById('root'));
module.hot.accept();
这是我的 index.ejs 文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><script defer src="main.bundle.js"></script></head>
<body>
<div id="root">
</div>
<script src="main.bundle.js"></script>
<% for (var css in htmlWebpackPlugin.files.css) { %>
<link href=".<%= htmlWebpackPlugin.files.css[css] %>" rel="stylesheet" />
<% } %>
</body>
</html>
这是 webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const webpack = require('webpack');
module.exports = (env, args) => {
return {
entry: './src/index.jsx',
...(options()),
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.scss$/i,
use: ['style-loader', 'css-loader', 'sass-loader'],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
],
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
plugins: plugins(),
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
}
};
};
const plugins = () => {
const resOut = path.resolve(__dirname, 'dist');
const plugs = [
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: [resOut],
dry: false,
}),
new HtmlWebpackPlugin({
hash: true,
filename: path.resolve(resOut, 'index.html'),
template: './src/index.ejs',
})
]
return plugs;
}
const options = () => {
const ops = {
mode: 'development',
devtool: 'eval-source-map',
devServer: {
contentBase: path.resolve(__dirname, 'dist'),
compress: true,
port: 9000,
historyApiFallback: true,
openPage: '',
hot: true,
proxy: {
'/api/**' : {
target: 'http://localhost:3000',
secure: false,
}
},
allowedHosts: [
'localhost',
]
},
};
return ops;
}
我也在使用这个小批量脚本来运行 webpack 开发服务器并启动 Express:
@echo off
cd %~dp0
start cmd.exe /k npm run serve
start node ./express/app.js
npm run build -- --watch
I'm not sure if this is related,但 React 开发工具显示“App”被渲染了 3 次。我不确定这是否是开发工具的一些怪癖,或者它是否可能导致一些问题。再次,我试图找出是否有人经历过类似的事情,但找不到任何东西。
我很高兴与您分享任何其他可能需要的信息,以了解这一点。提前感谢您提供的任何帮助。
【问题讨论】:
标签: javascript reactjs webpack