新建
新建一个文件夹,每个项目都有一个静态文件夹public和src src里面有一个项目主入口文件 main.js cnpm init -y 生成一个默认package.json记录项目的插件,写脚本之类的 写一个webpack.config.js用来写入项目的配置文件
安装
插件的安装可以项目依赖也可以开发依赖
1. 安装react和react-dom
cnpm i react -S cnpm i react-dom -S
2.在webpack.config.js写入以下代码就可以进行打包了
var path = require('path')
module.exports = {
mode:'development',
entry:['./src/main.js'],
output:{
path:path.resolve(__dirname,'dist'),
filename:'js/[name].[fullhash:8].js',
publicPath:''
}
}
3. 配置开发服务器
devServer:{
host:'0.0.0.0',
port:9000,
open:true,
hot:true,
compress:true,
liveReload:true
}
4. 浏览器插件
cnpm i webpack-open-browser-plugin -D 下载插件
var path = require('path')
var webpackOpenBrowserPlugin = require('webpack-open-browser-plugin')
module.exports = {
mode:'development',
entry:['./src/main.js'],
output:{
path:path.resolve(__dirname,'dist'),
filename:'js/[name].[fullhash:8].js',
publicPath:''
},
devServer:{
host:'0.0.0.0',
port:9000,
open:true,
hot:true,
compress:true,
liveReload:true
},
plugins:[
new webpackOpenBrowserPlugin({
url: 'http://localhost:9000'
})
]
}
5. 打包html
安装html-webpack-plugin cnpm i html-webpack-plugin -D
var path = require('path')
var webpackOpenBrowserPlugin = require('webpack-open-browser-plugin')
var htmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode:'development',
entry:['./src/main.js'],
output:{
path:path.resolve(__dirname,'dist'),
filename:'js/[name].[fullhash:8].js',
publicPath:''
},
devServer:{
host:'0.0.0.0',
port:9000,
hot:true,
compress:true,
liveReload:true
},
plugins:[
new webpackOpenBrowserPlugin({
url: 'http://localhost:9000'
}),
new htmlWebpackPlugin({
inject:true,
minify:true,
template:'./public/index.html'
})
]
}
6. 在package.json写入脚本方便起服务器跟打包
{
"name": "reactcli",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --hot",
"build": "rimraf dist && webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"webpack": "^5.73.0",
"webpack-open-browser-plugin": "^1.0.7"
}
}
7. 部分需要的react插件
cnpm i html-webpack-plugin -D cnpm i webpack-open-browser-plugin -D cnpm i babel-loader@7 babel-core@6 babel-preset-env -D cnpm i url-loader file-loader -D cnpm i mini-css-extract-plugin style-loader css-loader sass sass-loader less less-loader -D cnpm i react react-dom -S cnpm i babel-preset-stage-0 -D cnpm i prop-types -D cnpm i swiper@4 -S cnpm i babel-plugin-transform-runtime -D cnpm i react-router-dom -S cnpm i redux-thunk redux-promise -S cnpm install babel-plugin-transform-decorators-legacy --save-dev cnpm i immutable redux-immutable -S cnpm i mobx@5 mobx-react@6 -S
现在可以开启你的react项目了
|