基本命令

  1. './node_modules/.bin/webpack' webpack//进行基本打包功能
  2. npx webpack //以上功能简写

mode

webpack.config.js中配置

mode:'development',
或者'production'

入口出口

webpack.config.js基本配置代码

const path = require('path');

module.exports = {
    mode:'development',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  }
};

http缓存

访问网站时,css或者js一般加载到浏览器保存一年,但html每次都会重新加载
后缀的代码不同可以分辨是否需要加载新内容
更改生成文件的后缀使用如下形式:

filename:'[name].[contenthash].js'

script命令

用&&连接

"npx":"rm -rf dist && npx webpack"
可以运行 npm run npx

.gitignore

不提交的放入.gitignore,比如

/dist/ 
/node_modules/

html-webpack-plugin

 webpack中:
 var HtmlWebpackPlugin = require('html-webpack-plugin');
 plugins: [
    new HtmlWebpackPlugin({
      filename: 'test.html',
      title:'我的网站'
      template: 'src/assets/test.html'
    })
  ]
html中:
  template模板网页里加
  <title><%= htmlWebpackPlugin.options.title %></title>

  meta里用淘宝的name="viewport"

webpack-dev-server

webpack中:
devServer: {
    contentBase: './dist',
  }

package.json中:
script:
"start": "webpack serve --open"

style-loader,css-loader

webpack中:
module: {
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            }
        ]
    },

MiniCssExtractPlugin

用来提取css文件
style-loader和抽取css文件的plugin二选一

记得首先要require
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

webpack中:
plugins: [
    new MiniCssExtractPlugin({
            filename: '[name].[contenthash].css',
            chunkFilename: '[id].[contenthash].css',
            ignoreOrder: false
        })
  ]

 module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it uses publicPath in webpackOptions.output
              publicPath: '../'
            }
          },
          'css-loader',
        ],
      },
    ],
  },

file-loader

功能:加载图片等文件,把文件变成文件路径
步骤:

  1. 引入文件import png from ‘路径’,书写相关代码
  2. 把路径放入src里面
  3. 配置webpack.config.js

举例:

js文件中:
import jpg from './b5.jpg'

const pic = document.querySelector('#pic')
pic.innerHTML = `
<img src='${jpg}'>
`
包括上面的css插件
webpack.config.js中:
module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            publicPath: '../'
                        }
                    },
                    'css-loader',
                ],
            },
            {
                test: /\.(png|jpe?g|gif)$/i,
                use: [
                    {
                        loader: 'file-loader',
                    },
                ],
            },
        ]
    },