部门新来小学妹找我,想学webpack帮她男朋友做项目,这样她男朋友就有时间陪她了,我虽然很忙,还是放下来手中的工作,开始搭建这样一个项目,过程记录如下:
1.准备工作
我默认你已经安装了node.js,并且你的网络处于畅通的状态
2. 初始化项目
1.创建一个文件夹,以后所有的操作都是在这个文件夹中进
-在文件夹中创建
//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>Document</title>
</head>
<body>
<div>
1213212313
</div>
<script src="/dist/main.js"></script>
</body>
</html>
// webpack.config.js
var path = require('path');
var config ={
entry:{
main:"./main"
},
output:{
path:path.join(__dirname,'./dist'),
publicPath:'/dist/',
filename:'main.js'
}
}
module.exports = config;
其他文件 , src main.js和index.js暂时是空文件
2.打开一个终端使用npm init命令初始化项目生成package.json文件
{
"name": "fordemoone",
"version": "1.0.0",
"description": "learn notes",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --open --config webpack.config.js"
},
"author": "郑文浩",
"license": "ISC",
"devDependencies": {
}
}
这个时候你获取的文件可能是这样的,但是这事实上是才刚刚开始
3.正式开始安装三个重要依赖
"webpack"
"webpack-cli"
"webpack-dev-server"
- 首先是npm install webpack --save -dev
其次是npm install -g webpack-dev-server
最后下载 npm run -D webpack-cli
这个时候的package文件已经变化了
{
"name": "fordemoone",
"version": "1.0.0",
"description": "learn notes",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --open --config webpack.config.js"
},
"author": "郑文浩",
"license": "ISC",
"devDependencies": {
"webpack": "^5.24.2",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2"
}
}
按说这个时候应该已经可以通过npm run dev 启动项目了,
但是启动的时候报错了,这个错误很简单,就是版本的问题
在别的地方找到了解决方法
If you upgrade webpack to 5. *, and webpack cli to 4. *, an error will be reported:
Error: Cannot find module ‘webpack-cli/bin/config-yargs’
Temporary solution: Back off webpack cli to version 3. * for example:
“webpack-cli”: “^ 3.3.12”
所以我们需要卸载后重新安装低版本webpack-cli执行
npm uninstall webpack-cli
npm install webpack-cli@3 -D
修改之后的package.json
{
"name": "fordemoone",
"version": "1.0.0",
"description": "learn notes",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --open --config webpack.config.js"
},
"author": "郑文浩",
"license": "ISC",
"devDependencies": {
"webpack": "^5.24.2",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.2"
}
}
然后重启npm run dev 项目启动成功
4 总结,虽然上面写的过程看似顺利,但是作者在安装的过程中也是遇到了众多的难题都是博客堆里摸爬滚打过来的唯一的经验就是敢于尝试,擅于甄别一些高质量的教程,避免走弯路,让我们开始怀疑自己的智商,好在最终我还是完成了任务,想到学妹明天就能早早的下班和她男朋友开心的玩耍了,我感觉好欣慰
转载:https://blog.csdn.net/zhengwenhaodezw/article/details/114232125