初始化
- 创建项目文件夹
design - 创建
package.json文件
➜ design npm init - 安装
webpack以及webpack-cli
➜ design npm i webpack webpack-cli --save-dev
模块打包
- 创建打包配置文件
webpack.dev.config.js - 创建入口文件
./src/index.js - 编辑打包配置文件
module.exports = {
entry: './src/index.js',
output: {
path: __dirname,
filename: './release/bundle.js'
}
}
- 创建打包命令
package.json文件
"scripts": {
"dev": "webpack --config ./webpack.dev.config.js --mode development"
}
- 执行打包命令
npm run dev
此时,生成release文件夹,内部有打包后文件bundle.js。
热更新
- 安装依赖
➜ design npm i webpack-dev-server html-webpack-plugin --save-dev - 创建
html模板文件
./index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>前端设计模式</title>
</head>
<body>
<h1>前端设计模式</h1>
</body>
</html>
- 编辑打包配置文件
webpack.dev.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.js',
output: {
path: __dirname,
filename: './release/bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
template: './index.html'
})
],
devServer: {
open: true, //浏览器自动打开
port: 9000
}
}
- 编辑打包命令
package.json文件
"scripts": {
"dev": "webpack-dev-server --config ./webpack.dev.config.js --mode development"
},
- 执行打包命令
npm run dev
此时,浏览器自动打开http://localhost:9000,以./index.html为模板,以./release/bundle.js为JavaScript脚本。且实现热更新(修改./src/index.js文件时,浏览器自动刷新)。
开发调试
- 编辑打包配置文件
webpack.dev.config.js
module.exports = {
//...
devtool: 'eval-source-map',
//...
}
代理
- 编辑打包配置文件
webpack.dev.config.js
module.exports = {
//...
devServer: {
open: true, //浏览器自动打开
port: 9000,
proxy: {
'/api/*': {
target: 'http://localhost:8880'
//访问hocalhost:9000/api:*时,会被代理到hocalhost:8880/api:*
}
}
}
}
此时,访问hocalhost:9000/api:*时,会被代理到hocalhost:8880/api:*。
ES6语法
- 安装依赖
npm install babel-loader@7 babel-core babel-preset-env --save-dev - 编辑打包配置文件
webpack.dev.config.js
module.exports = {
// ...
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env'],
plugins: []
}
}
}]
},
//...
}
ES7语法
- 安装依赖
npm install babel-preset-stage-0 --save-dev - 编辑打包配置文件
module.exports = {
// ...
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ["env","stage-0"],
plugins: []
}
}
}]
},
//...
}
ES7提案-装饰器
- 安装依赖
npm install babel-plugin-transform-decorators-legacy --save-dev - 编辑打包配置文件
webpack.dev.config.js
module.exports = {
// ...
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ["env","stage-0"],
plugins: ["transform-decorators-legacy"]
}
}
}]
},
//...
}









网友评论