webpack
0配置使用步骤
- 要有
nodeJs
- 下载
webpack和webpack-cli
- 运行脚本
webpack
- 注意 由于是0配置,所以项目中必须得有
.src/index.js文件
package.json(包管理配置文件)
"devDependencies":{ 开发环境用的包,到了生产环境就用不到了 }
"dependencies":{开发和生产环境都能用到的包}
"scripts":{配置脚本命令}
"scripts": {
"dev":"webpack"
},
运行 npm run dev 相当于 npx webpack
webpack.config.js(webpack配置文件)
const { resolve } = require('path');
const HtmlPlugin = require('html-webpack-plugin');
const htmlPlugin = new HtmlPlugin({
template:'./src/index.html',
filename:'./index.html',
})
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: resolve(__dirname, './dist/'),
filename: 'bundle.js',
},
module:{
rules:[
{ test: /\.css$/, use: ['style-loader' , 'css=loader'] }
]
}
plugins:[htmlPlugin],
devServer:{
open:true,
hot:true,
port:5000,
contentBase:'./src',
}
}
webpack-dev-server(自动打包插件)
- 先安装
npm i -D webpack-dev-server
- 再在webpack.config.js配置,然后运行脚本
webpack serve
- 或者直接运行脚本
npx webpack-dev-server --hot --port 5000 --open --contentBase ./src
html-webpack-plugin(处理.html文件)
- 先安装
html-webpack-plugin
- 再在webpack.config.js配置
1. 先导入
const HtmlPlugin = require('html-webpack-plugin');
2. 创建实例对象
const htmlPlugin = new HtmlPlugin({
template:'./src/index.html',
filename:'./index.html',
})
3. 把实例对象挂载到 plugins属性中,使插件生效
plugins:[htmlPlugin]
- 运行脚本
npx webpack
处理css文件(其他文件大同小异)
- 安装
style-loader和css-loader
- 再在webpack.config.js配置
module:{
rules:[
{ test: /\.css$/, use: ['style-loader' , 'css=loader'] }
]
}
loader调用过程
- webpack默认只能打包处理
.js文件,如果用到其他文件
- 则会查找
webpack.config.js中的module.rules数组,看是否配置了对应的loader加载器
- 然后会把非
.js文件转交给对应的loader去处理
- 处理好之后叫会给webpack,然后合并到
出口文件.js中,最终生成打包好的文件