使用webpack 5搭建一个自己的react应用(一)打包应用
新建一个文件夹
mkdir webpack-react
设置为npm仓库
npm init
安装webpack,react包
npm install webpack webpack-cli --save-dev
npm install react react-dom -S
创建配置文件 webpack.config.js
touch webpack.config.js
创建应用入口文件 index.js
touch index.js
修改webpack配置文件
module.exports = {
entry: './index.js',
output: {
filename: '[name].js',
},
};
与此同时,我们还需要修改index.js
import React from 'react';
import reactDOM from 'react-dom';
function App() {
return <div className="App">first react webpack app</div>;
}
reactDOM.render(<App />, document.getElementById('app'));
修改package.json,新增build命令
"scripts": {
"build": "webpack"
},
执行 npm run build
发现会报错
assets by status 334 bytes [cached] 1 asset
./index.js 201 bytes [built] [code generated] [1 error]
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value.
Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/
ERROR in ./index.js 5:9
Module parse failed: Unexpected token (5:9)
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
|
| function App() {
> return <div className="App">first react webpack app</div>;
| }
|
这报错提示我们jsx语法未能识别,需要安装能解析jsx的loader
npm install --save-dev @babel/core @babel/preset-env @babel/preset-react babel-loader
新建babel的配置文件,并修改
touch .babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"],
"plugins": []
}
接着我们修改webpack.config.js新增babel-loader
创建src文件夹,这里我们将index.js放入src里,然后我们的loader包含src,只对src里的文件做处理
mkdir src && mv ./index.js ./src
const path = require('path')
const basePath = path.resolve(__dirname, 'src');
module.exports = {
entry: ‘./src/index.js',
output: {
filename: '[name].js',
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ['babel-loader'],
include: basePath,
},
],
},
};
运行npm run build 可以发现已经生成dist文件夹,里面有我们打包过后的文件
创建index.html
现在我们只是有了打包后的js文件,但是没有html入口文件,我们新建一个
touch index.html
修改 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>webpack-react-demo</title>
</head>
<body>
<div id="app"></div>
<script src="./dist/main.js"></script>
</body>
</html>
我们打开文件index.html,发现页面上也可以正常展示出first react webpack app
了
我们将代码传到gitee
https://gitee.com/semyin/webpack-react
touch .gitignore
修改.gitignore文件
.DS_Store
node_modules/
dist/
grey/
test/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
package-lock.json
tests/**/coverage/
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.history
# webstorm webpack alias config
webstorm.config.js
Dockerfile
.dockerignore
docker-compose.yml
git add .
git commit -m ‘init’
git push origin master