1-1 核心概念

  1. Entry
  2. | 代码的入口,打包的入口。
  3. Output
  4. | 打包文件的(bundle)所在的目录
  5. Loader
  6. | 可以处理非js文件
  7. Plugins
  8. | 可以参与打包的整个过程,打包优化压缩
  9. mode
  10. | development/production

1-2 起步

  1. cnpm init -y //生产package.json的文件
  1. cnpm i webpack webpack-cli -S
  1. // webpack.config.js
  2. const webpack = require("webpack");
  3. const path = require("path");
  4. const HtmlWebpackPlugin = require('html-webpack-plugin');
  5. const {CleanWebpackPlugin} = require("clean-webpack-plugin")
  6. const {VueLoaderPlugin} = require("vue-loader")
  7. const config = {
  8. entry:path.resolve(__dirname,'src/main.js'), //入口文件
  9. output:{ //出口文件
  10. path:path.resolve(__dirname,'dist'),
  11. filename:'bundle.js'
  12. },
  13. module:{
  14. rules:[
  15. {
  16. test:/\.css$/i,
  17. use:['style-loader','css-loader']
  18. },
  19. {
  20. test:/\.vue$/,
  21. loader:'vue-loader'
  22. },{
  23. test:/\.(png|jpg|svg|gif|jpeg)$/i,
  24. type:'asset/resource'
  25. }
  26. ]
  27. },
  28. plugins:[
  29. new HtmlWebpackPlugin({
  30. title:"webpack-vue",
  31. template:path.resolve(__dirname,"public/index.html")
  32. }),
  33. new CleanWebpackPlugin(),
  34. new VueLoaderPlugin()
  35. ],
  36. devtool: 'inline-source-map',
  37. devServer:{
  38. contentBase:"./dist",
  39. port:8000,
  40. host:"localhost",
  41. overlay:{
  42. errors:true
  43. }
  44. },
  45. mode:'development' //模式
  46. }
  47. module.exports = config;
  1. //配置package.json文件
  2. {
  3. // 删除"main"入口配置添加"private"为true
  4. "private": true
  5. "scripts": {
  6. "build": "webpack --config webpack.config.js"
  7. }
  8. }
  1. // 打包
  2. npm run build

1-3 loader

  1. wepack自身只能处理jsjson文件,加上loader后,能让wepack去处理非js(css)的文件。loader可以将所有类型的文件转换为webpack能够处理的有效模块。

项目加载css

Tips:loader是配置在module中的

  1. cnpm i style-loader css-loader -S
  1. const webpack = require("webpack");
  2. const path = require("path");
  3. const config = {
  4. entry:path.resolve(__dirname,'src/main.js'), //入口文件
  5. output:{ //出口文件
  6. path:path.resolve(__dirname,'dist'),
  7. filename:'bundle.js'
  8. },
  9. + module:{
  10. + rules:[
  11. + {
  12. + test:/\.css$/i,
  13. + use:['style-loader','css-loader']
  14. + }
  15. + ]
  16. + },
  17. mode:'development' //模式
  18. }
  19. module.exports = config;

1-4 plugins

1-4-1 给打包文件一个html文件

  1. cnpm i html-webpack-plugin -S
  2. //自动生成index.html文件
  1. ...
  2. +const HtmlWebpackPlugin = require('html-webpack-plugin');
  3. const config = {
  4. ....
  5. + plugins:[
  6. + new HtmlWebpackPlugin({
  7. + title:"webpack-vue",
  8. template:path.resolve(__dirname,"public/index.html")
  9. + })
  10. + ],
  11. mode:'development' //模式
  12. }
  13. module.exports = config;

1-4-2 清除dist文件夹

  1. cnpm i clean-webpack-plugin -S
  2. //清除dist目录下需要的文件
  1. + const {CleanWebpackPlugin} = require("clean-webpack-plugin");
  2. const config = {
  3. ...
  4. plugins:[
  5. ...
  6. + new CleanWebpackPlugin()
  7. ],
  8. mode:'development' //模式
  9. }