webpack开发环境及生产环境基本配置
webpack(开发环境)
node-v
npm init -y
npm install webpack webpack-cli -D
新建一个index.js文件
新建一个index.html文件
npm install webpack-dev-server -D
npm install html-webpack-plugin -D
const path = require('path')
const HtmlWebpackPlugin = 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 HtmlWebpackPlugin({
template:path.join(__dirname,'src','index.html'),
filename:'index.html',
})
],
devServer:{
port:3000,
contentBase:path.join(__dirname,'dist')
}
}
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"dev": "webpack-dev-server"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^5.4.0",
"webpack-cli": "^4.2.0",
"webpack-dev-server": "^3.11.0"
}
}
npm run build
npm run dev
npm install @babel/core @babel/preset-env babel-loader -D
{
"presets": ["@babel/preset-env"]
}
module:{
rules:[
{
test:/\.js$/,
loader:['babel-loader'],
include:path.join(__dirname,'src'),
exclude:/node_modules/
}
]
},
webpack(生产环境)
webpack.prod.js
const path = require('path')
const HtmlWebpackPlugin = 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 HtmlWebpackPlugin({
template:path.join(__dirname,'src','index.html'),
filename:'index.html',
})
]
}
package.json 需要修改
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.prod.js",
"dev": "webpack-dev-server"
},
通过npm run build 进行打包
执行npm run dev 之后浏览器打开http://localhost:3000/ 进行查看