起源:因为最近一直用jQuery写H5页面,觉得挺无聊的,想着用webpack配置一个项目来开发H5页面,就可以使用NPM无穷无尽的包了, 然后就可以随便浪了。
基本步骤:
一、初始化基本环境
npm init
这个不多说,自己设置。
npm install webpack webpack-cli --save-dev
二、建index.html
index.js
webpack.config.js
文件,具体位置如下
1、index.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script type="text/javascript" src="./bundle.js"></script>
</body>
</html>
2、index.js文件
console.log("Hello World!");
3、webpack.config.js文件
const path = require("path");
module.exports = {
entry: path.resolve(__dirname, "src/index.js"),
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
},
};
4、修改package.json文件,然后运行npm run build 查看效果,在控制台看到输出Hello World!
就算成功了。
{
"name": "webpacktest1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.config.js"
},
"author": "sq",
"license": "ISC",
"devDependencies": {
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12"
}
}
三、实现热加载。
1、安装 npm install webpack-dev-server -D
2、修改webpack.config.js文件
const path = require("path");
module.exports = {
entry: path.resolve(__dirname, "src/index.js"),
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
},
devServer: {
port: "8000",
contentBase: "./dist",
host: "localhost",
hot: true, //热加载
},
};
3、修改package.json
文件,并运行npm run start
,然后修改index.js
里面的输出内容,可以在浏览器控制台看到数据会实时更新。
{
"name": "webpacktest1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --progress --config webpack.config.js",
"build": "webpack --config webpack.config.js"
},
"author": "sq",
"license": "ISC",
"devDependencies": {
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
}
}
最后: 一个最简单的基本项目就搭建完成了,后续可以根据需要安装各种loader以及插件,例如:css预处理器,Babel等loader,代码拆分、删除重复的打包文件插件等等。也可以将webpack配置为开发环境和生产环境,建立webpack.base.config.js
webpack.dev.config.js
webpack.prod.config.js
三个文件,然后安装webpack-merge
插件进行配置,即可完成。
突然有点不满足这些配置,下一篇想配置一个vue的开发环境玩玩。