基本配置
安装webpack
先安装webpack 和webpack-cli
npm i webpack webpack-cli -D
创建src文件夹并设置index.js文件
index.js中写入
console.log(12);
创建webpack.config.js
当前目录如下
配置webpack.config.js文件如下
const path = require('path')
module.exports={
entry:'./src/index.js',//入口文件
output:{
filename:'index.js',//文件名
path:path.resolve(__dirname,'dist')//打包后的路劲
}
}
在Learnwebpack中cmd执行命令
npx webpack
此时生成dist目录,在其中添加一个index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
<script src="./index.js"></script>
</html>
执行文件可以发现控制台输出了12
托管至服务器执行
安装
npm i webpack-dev-server -D
在webpack.config.js中配置
devServer:{
port:3008,//配置服务器端口
contentBase:'./dist' //打包的路径
}
在Learnwebpack中cmd执行命令
npx webpack-dev-server
此时访问 http://localhost:3008/ 即可执行dist中的html文件
ps:可在package.json中的script中写入如下命令
"build": "webpack",
"dev": "webpack-dev-server"
之后执行
npm run build //相当于npx webpack
npm run dev //相当于npx webpack-dev-server