前言
基于:很多时候需要做一些比较简单的demo测试,不需要使用cra或者vite去全量新建项目,保证测试一些功能的时候,保证结果的准确性,所以需要一个简单的react+webpack运行时的基础项目。
搭建react+webpack的基础demo主要分为babel环境和webpack环境的搭建
文件结构
新建如下文件和文件夹
├── package-lock.json
├── package.json
├── public
│ └── index.html
├── src
│ ├── App.tsx
│ └── index.tsx
├── .babelrc
├── tsconfig.json
└── webpack.config.js
安装依赖
npm install --save react react-dom
npm install --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin babel-loader @babel/core @babel/preset-env @babel/preset-react typescript ts-loader
文件配置
.babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": false,
"strictNullChecks": false,
"strictBindCallApply": true,
"module": "esnext",
"target": "esnext",
"jsx": "react-jsx",
"allowJs": true,
"strict": false,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"baseUrl": ".",
"incremental": true,
"tsBuildInfoFile": "./buildFile",
"diagnostics": true,
"noUnusedLocals": true,
"jsxImportSource": "react",
},
"include": ["./src/**/*"],
"exclude": ["./node_modules"],
"compileOnSave": false,
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const isProduction = process.env.NODE_ENV === 'production';
module.exports = {
entry: './src/index.tsx',
mode: isProduction ? 'production' : 'development',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.bundle.js',
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
module: {
rules: [
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
},
},
'ts-loader',
],
},
{
test: /.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true
}
},
{ loader: 'sass-loader' }
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
}),
],
};
package.json
修改命令
"scripts": {
"start": "NODE_ENV=development webpack serve --open",
"build": "NODE_ENV=production webpack"
},
src/App.tsx
// src/App.tsx
const App = () => {
return <div> webpack + react </div>
}
export default App
src/index.tsx
// index.tsx
import ReactDOM from 'react-dom/client'
import App from './App'
const root = ReactDOM.createRoot(document.getElementById('app')!)
root.render(<App />)
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React App</title>
</head>
<body>
<div id="app"></div>
</body>
</html>