使用webpack工具打包资源,启动程序
npm run dev
此时出现报错:
The CLI moved into a separate package: webpack-cli Please install
‘webpack-cli’ in addition to webpack itself to use the CLI
-> When using npm: npm i -D webpack-cli
-> When using yarn: yarn add -D webpack-cli internal/modules/cjs/loader.js:883 throw err; ^Error: Cannot find module ‘webpack-cli/bin/config-yargs’ Require
stack:
经过上网搜索,发现出现这个错误的主要原因有如下三个:
- webpack的版本与webpack-dev-server的版本不兼容,例如两个版本都是3.X,则不能兼容
- webpack-cli 包已经从webpack分离出来了,因此需要额外安装webpack-cli包
- webpack-cli的版本和webpack-dev-server不兼容,webpack-cli的版本号过高
我们上面报错,原因1的可能性不大(webpack5.27.1和webpack-dev-server3.11.2应该是兼容的)从日志中看,更有可能是原因2
因此用命令添加webpack-cli:
cnpm install webpack-cli --save-dev
安装完成后,我们再用npm run dev启动,发现仍然报错
-> webpack_demo@1.0.0 dev E:\WorkSpace\H5\vue\learn\webpack_demo_2
-> webpack-dev-server --host localhost --port 8888 --open --config webpack.config.jsinternal/modules/cjs/loader.js:883 throw err; ^
Error: Cannot find module ‘webpack-cli/bin/config-yargs’ Require
stack:
但这次日志没有直接指出缺少webpack-cli包,说明确实是需要独立安装webpack-cli的。现在的报错可能是原因3,我们检查webpack.config.js,发现版本如下:
"devDependencies": {
"webpack": "^5.27.1",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2"
}
webpack-cli版本为4.5.0,比webpack-dev-server3.11.2高很多,因此对其降级。改为合适的版本
"webpack-cli": "^3.3.12",
webpack.config.js
做修改,改为以上版本node_modules
文件夹cnpm i
,让nodejs加载webpack.config.js中已经写好的依赖包版本用命令卸载高版本webpack-cli
npm uninstall webpack-cli -g 卸载全局
npm uninstall webpack-cli -D 卸载局部(本地)
再安装指定版本的 webpack-cli@3.3.12
cnpm install webpack-cli@3.3.12 --save-dev
两种办法选其一,即可成功启动程序
webpack.config.js配置如下:
var path = require('path');
var config = {
entry: {
main: './main'
},
output: {
publicPath: '/dist/',
path: path.join(__dirname, './dist'),
filename: 'main.js'
}
};
module.exports = config;
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>webpack App</title>
<link rel="stylesheet" type="text/css" href="/dist/main.css">
</head>
<body>
<div id="app">
Hello World.
</div>
<script type="text/javascript" src="/dist/main.js"></script>
</body>
</html>
通过如下cmd命令,加载了必要的依赖:webpack、webpack-dev-server
cnpm install webpack --save-dev
cnpm install webpack-dev-server --save-dev
此时发现,package.json中添加依赖版本如下:
{
"name": "webpack_demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --host localhost --port 8888 --open --config webpack.config.js"
},
"author": "Albert Guo",
"license": "ISC",
"devDependencies": {
"webpack": "^5.27.1",
"webpack-dev-server": "^3.11.2"
}
}