我开始使用Webpack(v5)和React(v18),我真的很纠结于如何配置Webpack文件来自动生成包含HTML和JS文件的dist文件夹,非常感谢您的帮助:
我的webpack配置、package.json和index.js文件如下所示:
Webpack文件:
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: "development",
devServer: {
static: "./dist",
host: 'localhost',
port: 8563,
open: true,
},
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "../dist"),
filename: "bundle.js",
clean: true,
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.(gif|png|jpe?g|svg)$/i,
use: [
"file-loader",
{
loader: "image-webpack-loader",
options: {
bypassOnDebug: true, // webpack@1.x
disable: true, // webpack@2.x and newer
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
filename: "index.html",
inject: 'body'
}),
],
devtool: "inline-source-map",
};
package.json文件:
{
"name": "dashboard",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack serve --mode development --config config/webpack.config.js",
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@wojtekmaj/enzyme-adapter-react-17": "^0.6.7",
"@zarconontol/enzyme-adapter-react-18": "^0.7.3",
"clean-webpack-plugin": "^4.0.0",
"css-loader": "^6.7.1",
"file-loader": "^6.2.0",
"image-webpack-loader": "^8.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"style-loader": "^3.3.1"
},
"devDependencies": {
"@babel/core": "^7.19.3",
"@babel/preset-env": "^7.19.3",
"@babel/preset-react": "^7.18.6",
"@testing-library/react": "^13.4.0",
"babel-loader": "^8.2.5",
"chai": "^4.3.6",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.6",
"enzyme-to-json": "^3.6.2",
"html-webpack-plugin": "^5.5.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^29.1.1",
"jest-transform-stub": "^2.0.0",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.1"
}
}
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
HTML档案
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
先谢谢你了
1条答案
按热度按时间relj7zay1#
由于您使用
start
命令运行webpack
dev服务器,这意味着它可能会在内存上编译和提供资产,而不是本地磁盘,我认为这就是原因。因此,为了在本地磁盘上生成资产,您需要运行不带serve
选项的webpack
cli,让我们创建一个build
命令,如:对于html模板,您不必在其中包含脚本文件,
webpack
插件会为您处理它。因此,您只需为React应用指定要初始化的div#root
:index.html