1. 新建项目
yarn init
2. 安装
- 安装webpack到开发环境
yarn add webpack --dev
2.安装webpack-dev-server到开发环境
yarn add webpack-dev-server --dev
3.安装webpack-cli到开发环境
yarn add webpack-cli --dev
如果不安装,在后续配置运行 npm run dev
的时候会报错:(有说是因为版本不同所以才会报错,反正就安装上吧)
Cannot find module 'webpack-cli/bin/config-yargs'
3. 配置
- 根目录下新建webpack.config.js (webpack运行默认文件名),写入: (这里是入口和输出以及文件配置,只要整个文件在
webpack
命令下跑通,就没问题。具体的src文件和index.html文件还是要自己配置。)
const path = require('path') //node的路径模块
module.exports = {
entry: {
app: ["./src/index.js"] //入口文件
},
output: {
path: path.resolve(__dirname, "build"),//输出位置
publicPath: "/assets/",//指定资源文件引用的目录
filename: "bundle.js"//输入文件
}
}
- 在package.json中的script写入
"dev": "webpack-dev-server --open"
。此时package.json的内容有:
{
"name": "webpack-server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --open",
"build": "webpack"
},
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.10.1",
"webpack-cli": "^2.1.4",
"webpack-dev-server": "^3.1.4"
}
}
4. 运行
运行 npm run dev
就会自动新建页面展示,并即时刷新了。
网友评论