1.初始化配置package.json
npm init
2.安装webpack
npm install webpack --save-dev
3.安装webpack-cli
npm install webpack-cli --save-dev
4.安装webpack-dev-server 用于启动服务
npm install webpack-dev-server --save-dev
5.创建webpack.config.js (于根目录手动创建并写入内容)
var path = require('path');
var config = {
entry: {
main: './index' //入口文件
},
output: {
path: path.join(__dirname, './dist'), //打包后输出目录名
publicPath: '/dist/',
filename: 'index.js'
}
}
module.exports = config;
6.在package.json里面配置如下(scripts代码部分,配置webpack-dev-server的命令)
8080 //是配置的端口号,如果端口号冲突可自行更改成其他端口号
npm run dev //运行可启动项目
npm run webpack //运行可生成dist
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --open --host localhost --port 8080 --config webpack.config.js",
"webpack": "webpack"
}
7.创建index.js (于根目录手动创建并写入内容)
console.log('1')
8.创建index.html (于根目录手动创建并写入内容)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>node</title>
</head>
<body>
<div id="app"> Hello World! </div>
<script src="/dist/index.js"></script>
</body>
</html>
9.启动项目
根目录打开cmd输入命令,启动后的地址为 http://localhost:8080/
npm run dev
附加: 可能遇到问题
问题.1
- 我这里webpack相关插件的默认版本是
"webpack": "^5.30.0",
"webpack-cli": "^4.6.0",
"webpack-dev-server": "^3.11.2"
- 报错如下
Error: Cannot find module 'webpack-cli/bin/config-yargs'
- 后来找了下解决方案
方案1.重装node_modules (无效)
方案2.然后把webpack的版本号换了下,结果可用正常运行(可以)
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.9.0"
问题.2
待添加...
以下是可用的package.json配置(可以直接全部复制到package.json里面),或者只复制webpack的版本号部分也行
{
"name": "node1",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --open --host localhost --port 8080 --config webpack.config.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.9.0"
},
"description": ""
}