1.搭建基础的结构框架
新建项目文件夹 myapp
在myapp根目录下初始化 npm init --yes
在myapp根目录下新建dist文件夹(用于存放编译好的东西),新建src文件夹(用于存放源代码)
2.安装webpack依赖
在myapp根目录下: npm install webpack webpack-cli webpack-dev-server --save-dev
3.构建基础代码结构
在myapp根目录下新建index.html(这是项目的入口html文件),引入bundle.js(这是编译好的代码文件,自动生成,无需创建)
如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>myapp</title>
</head>
<body>
</body>
<script src="bundle.js" charset="utf-8"></script>
</html>
在src目录下新建index.js文件,这是项目的入口文件,根据需要编写。本次测试,index.js内容如下
document.write("hello!This is webpack with HMR!");
4.配置webpack.config.js文件
在myapp根目录下新建webpack.config.js文件。webpack配置参数有五大要素:entry,output,module,plugins,mode
entry:项目的入口文件
output:编译好的输出文件
module:定义编译规则,哪种类型的文件对应用哪个loader
plugins:webpack插件
mode:模式,有两个值 分别是 "production" 和"development"
这次只用到entry,output,mode。还需追加devServer参数配置,因为需要项目运行在本地服务器上,采用基于express框架的webpack-dev-server,为达到热更新的效果,需要配置hot参数。
const path = require("path");
module.exports = {
entry:"./src/index.js",
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
mode: 'production',
devServer:{
hot:true,
inline:true
}
};
5.配置运行脚本package.json
在package.json文件中找到 "script"键,在里面追加编译脚本"server": "webpack-dev-server --mode production --inline --hot",如下
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"server": "webpack-dev-server --mode production --inline --hot"
},
6.运行npm run server
在localhost:8080可以看到如下。在index.js文件下修改对应的数据,保存,页面自动更新。