配置开发环境
- npm init -y
- cnpm install webpack webpack-cli -D
- 新建webpack.config.js
- 新建src文件夹,index.js文件
- 在package.json中添加"build":"webpack"后,运行npm run build
- 新建index.html文件
- cnpm install html-webpack-plugin -D //解析html的插件
- cnpm install webpack-dev-server -D //启动服务的插件
- webpack.config.js中配置
const path = require('path')
const htmlWebackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
entry: path.join(__dirname, 'src', 'index.js'),
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'dist')
},
plugins: [
new htmlWebackPlugin({
template: path.join(__dirname, 'src', 'index.html'),
filename: 'index.html'
})
],
devServer: {
port: 3000,
contentBase: path.join(__dirname, 'dist')
}
}
- 在package.json中添加"dev":"webpack-dev-server"后,运行npm run dev启动服务
- cnpm install @babel/core @babel/preset-env babel-loader -D
- 新建.babelrc文件,并配置
{
"presets": ["@babel/preset-env"]
}
- 在webpack.config.js里配置module
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: path.join(__dirname, 'src'),
exclude: /node_modules/
}
]
},
- 完整示例
const path = require('path')
const htmlWebackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
entry: path.join(__dirname, 'src', 'index.js'),
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: path.join(__dirname, 'src'),
exclude: /node_modules/
}
]
},
plugins: [
new htmlWebackPlugin({
template: path.join(__dirname, 'src', 'index.html'),
filename: 'index.html'
})
],
devServer: {
port: 3000,
contentBase: path.join(__dirname, 'dist')
}
}
配置生产环境
- 新建webpack.prod.js
- 拷贝webpack.config.js内容进行修改
mode:改为"production"
去掉devServer
output中file添加[contenthash],例如:‘bundle.[contenthash].js’ //为了缓存
- 修改package.json
build:改为’webpack --config webpack.prod.js’
- 完整示例
const path = require('path')
const htmlWebackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'production',
entry: path.join(__dirname, 'src', 'index.js'),
output: {
filename: 'bundle.[contenthash].js',
path: path.join(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: path.join(__dirname, 'src'),
exclude: /node_modules/
}
]
},
plugins: [
new htmlWebackPlugin({
template: path.join(__dirname, 'src', 'index.html'),
filename: 'index.html'
})
]
}