1,npm init -y 初始化项目,项目会多出一个package.json文件
2,npm install webpack webpack-cli -D 项目会多出一个node_modules文件
3,在项目中创建一个webpack.config.js文件
const path=require('path')
module.exports={
mode:'development',//开发模式,文件没有压缩,如果是生产项目,文件就会压缩,用production
entry:path.join(__dirname,'src','index.js'),
output:{
filename:'bundle.js',
path:path.join(__dirname,'dist')
}
}
在package.json中添加
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
运行npm run build,项目就会打包
以上是只有js,下面是有添加html的,
1,解析html的插件,npm install html-webpack-plugin
2,启动服务的插件,npm install webpack-dev-server
3,在webpack.config.js中进行插件配置
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')
}
}
4,在package.json中添加
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"dev":"webpack-dev-server"
},
5,运行npm run dev,然后在网页输入localhost:3000就可以访问
babel配置
1,npm install @babel/core @babel/preset-env babel-loader -D //core是核心,prese-env配置,babel-loader给webpack用的插件,
2,创建一个.babelrc文件,
{
"presets":["@babel/preset-env"]
}
3,在webpack.config.js中进行配置
module:{
rules:{
test:/\.js$/,
loader:['babel-loader'],
include:path.join(__dirname,'src')
}
}
配置生产环境的webpack
1,创建一个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')
}
}
plugins:[
new HtmlWebpackPlugin({
template:path.join(__dirname,'src','index.html'),
filename:'index.html'
})
]
}
2,更改package.json文件
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.prod.js",
"dev": "webpack-dev-server"
},