创建项目文件架 在文件夹中执行 npm init 之后生成 package.json文件
全局安装
执行npm install webpack webpack-cli -g
验证:webpack -v
删除全局安装 npm uninstall webpack webpack-cli -g
局部安装 (常用)
安装:npm install webpack webpack-cli --save-dev
例如我们要安装一个 webpack-dev-server,命令如下所示:
npm install webpack-dev-server --save-dev
npm install create-react-app
2 创建项目reactDemo,安装初始依赖
create-react-app reactDemo
3 安装 loaders 和 plugins
npm i @babel/[email protected] [email protected] @babel/[email protected]
npm i [email protected] [email protected]
npm i [email protected]
4 package.json
{
"name": "manuallyreact",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --open",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"@babel/core": "^7.12.3",
"@babel/preset-react": "^7.12.1",
"babel-loader": "^8.1.0",
"css-loader": "^5.0.0",
"html-webpack-plugin": "^4.5.0",
"react": "^16.14.0",
"react-dom": "^16.14.0",
"style-loader": "^2.0.0",
"webpack": "^4.44.2",
"webpack-cli": "^2.0.9",
"webpack-dev-server": "^3.0.0"
}
}
5 在根目录创建 webpack.config.js 配置webpack
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry:'./src/index.js',
output:{
path:path.resolve(__dirname,'dist'),
filename:"main.js"
},
devServer: {
contentBase: "./public",//本地服务器所加载的页面所在的目录
historyApiFallback: true,//不跳转
inline: true,//实时刷新
},
module:{
rules:[
{
test: /\.js$/,
exclude: path.resolve(__dirname, 'node_modules'),
include: path.resolve(__dirname, 'src'),
loader:'babel-loader',
options:{
presets: [
"@babel/react"
]
}
},
{
test: /\.css$/,
use:['style-loader','css-loader'] // 从右到左执行,所以注意顺序
}
]
},
plugins:[new htmlWebpackPlugin({
template:path.join(__dirname,'./public/index.html'),
filename: 'index.html'
})
],
}
6 创建项目
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Manually Reacttitle>
head>
<body>
<div id="root">div>
body>
html>
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
const App = (
<div className="border">
<h1>Manually React</h1>
</div>
)
ReactDOM.render(App,document.getElementById("root"));
.border{
border: 1px solid red;
border-radius: 10px;
margin: 10px;
text-align: center;
}
7 执行
npm start