一、核心概念

  1. Entry
  2. | 代码的入口,打包的入口,单个或多个入口
  3. Output
  4. | 打包成的文件(bundle) 一个或多个 自定义规则
  5. Loaders
  6. | 处理文件,转化为模块
  7. Plugins
  8. | 可以参与整个打包的过程
  9. | 打包优化和压缩
  10. | 配置编译时的变量
  11. mode

1-1 Entry,Output

定义多个入口文件,输入多个文件

webpack.config.js

const webpack = require('webpack');
const {
    resolve
} = require('path');
const config = {
    entry:{
        index:resolve(__dirname,'src/index.js'),
        vendor:resolve(__dirname,'src/vendor.js')
    },
    output: {
        path: resolve(__dirname, 'dist'),
        filename: "[hash]-[name]-bundle.js"
    },
    mode: 'development'
}
module.exports = config

package.json

"scripts": {
    "build":"webpack --config webpack.config.js"
 }

1-2 loader,plugins

loader 让 webpack 能够去处理那些非 JavaScript 文件(webpack 自身只理解 JavaScript)。loader 可以将所有类型的文件转换为 webpack 能够处理的有效模块,然后你就可以利用 webpack 的打包能力,对它们进行处理。

加载css

npm i style-loader css-loader -S
const webpack = require('webpack');
const {resolve} = require('path');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const config = {
    entry:{
        index:resolve(__dirname,'src/index.js'),
        vendor:resolve(__dirname,'src/vendor.js')
    },
    output: {
        path: resolve(__dirname, 'dist'),
        filename: "[hash]-[name]-bundle.js"
    },
    plugins:[
        new CleanWebpackPlugin()
    ],
+ module:{
+     rules:[
+         {
+                test:/\.css$/,
+                use:[
+                    'style-loader',
+                    'css-loader'
+                ]
+            }
+        ]
+   },
    mode: 'development'
}
module.exports = config
//常用的loader
- 编译相关
babel-loader ts-loader
- 样式相关
style-loader css-loader less-loader postcss-loader sass-loader
- 文件相关
file-loader url-loader

1-3 代码压缩

module.exports = {
  //...
  optimization: {
    minimize: true
  }
};