Mac OS上,初始化一个React项目
初始化项目
创建目录
1
| 在项目根目录下,创建src源代码目录和dist产品目录
|
创建首页文件
1
| 在src目录下创建index.html和index.js文件
|
安装webpack
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| cnpm i webpack -D
package.json内容如下: { "name": "react", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "webpack": "^5.66.0" } }
|
安装webpack-cli
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| cnpm i webpack-cli -D
package.json内容如下: { "name": "react", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "webpack": "^5.66.0", "webpack-cli": "^4.9.1" } }
|
设置环境变量
1 2
| echo 'export PATH="./node_modules/.bin:$PATH"' >> ~/.zshrc source ~/.zshrc
|
新建webpack配置文件
1 2 3 4 5 6 7
| 在项目根目录下新建:webpack.config.js
内容如下: //向外暴露一个打包的配置对象;因为webpack是基于Node构建的,所以,webpack支持所有Node Api和语法 module.exports = { mode : 'development' //'development' or 'production' }
|
注意:webpack4.x提供了约定大于配置的概念,目的是为了尽量减少配置文件的体积
- 打包入口:
src
-> index.js
- 打包的输出文件是
dist
-> main.js
- 4.x中新增了
mode
选项,可选的值为:development
和 production
执行打包
显示网页
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 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>Index 首页</title> <script src="../dist/main.js"></script> </head> <body> 这是首页 </body> </html>
|
安装webpack-dev-server
1
| cnpm i webpack-dev-server -D
|
在package.json中新增
1 2 3 4 5 6 7
| "dev":"webpack-dev-server"
内容如下: "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev":"webpack-dev-server" },
|
修改index.html里面的js路径
1 2 3 4 5
| <!-- <script src="../dist/main.js"></script> --> <script src="/main.js"></script> ```
> 运行
|
npm run dev
1 2
| **注意**:此时在浏览器输入:`http://localhost:8080/`有可能出现`cannot get`,解决方案:
|
npx webpack server –static src