查看webpack最新版本

  1. npm info webpack

image.png

全局安装

  1. npm i -g webpack@4 webpack-cli@4

局部安装

  1. mkdir webpack-demo
  2. cd webpack-demo
  3. npm init -y
  4. npm install webpack webpack-cli --save-dev
  5. # 或者
  6. yarn add webpack webpack-cli --save-dev

用webpack转译JS

安装完后查看版本

  1. ./node_modules/.bin/webpack --version

运行webpack

  1. npx webpack # 安装路径不能有空格

去除警告

image.png
在webpack-demo文件夹创建webpack.config.js文件,
写入内容, mode可以设为development或product

  1. module.exports = {
  2. mode: 'development'
  3. };

设置entry和output

  1. var path = require('path');
  2. module.exports = {
  3. mode: 'development',
  4. entry: './src/index.js', // 输入文件
  5. output: {
  6. // path: path.resolve(__dirname, 'dist'), // 路径默认是dist
  7. filename: 'index.js' // 输出文件名
  8. }
  9. };

HTTP缓存

缓存可以加快访问速度
通过Cache-Control设置max-age
如果index.html中的引用文件名变了,则下载新的文件
将output中的filename设置如下,则给文件名自动生成hash数字

  1. output: {
  2. filename: '[name].[contenthash].js'
  3. }

每次运行,应先删掉dist文件
在package.json文件的scripts中添加build
linux和mac系统中&&可改为;

  1. "scripts": {
  2. "build": "rm -rf dist && webpack",
  3. "test": "echo \"Error: no test specified\" && exit 1"
  4. },
  1. yarn build

生成html文件

安装插件

  1. yarn add html-webpack-plugin --dev

修改webpack.config.js
添加HtmlWebpackPlugin和plugins两行
参考:https://github.com/jantimon/html-webpack-plugin#options

  1. const HtmlWebpackPlugin = require('html-webpack-plugin')
  2. var path = require('path');
  3. module.exports = {
  4. mode: 'development',
  5. entry: './src/index.js',
  6. output: {
  7. // path: path.resolve(__dirname, 'dist'),
  8. filename: 'index.[contenthash].js' // [name]可以修改
  9. },
  10. plugins: [
  11. new HtmlWebpackPlugin()
  12. ]
  13. };

用自己的模板生成html

  1. plugins: [
  2. new HtmlWebpackPlugin({
  3. title: 'Custom template',
  4. // Load a custom template (lodash by default)
  5. template: 'src/index.html'
  6. })
  7. ]

自定义index.html的title

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8"/>
  5. <title><%= htmlWebpackPlugin.options.title %></title>
  6. </head>
  7. <body>
  8. </body>
  9. </html>

加载css文件

安装css-loader和style-loader

  1. yarn add css-loader --dev
  2. yarn add style-loader --dev

添加配置

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/i,
  6. use: ['style-loader', 'css-loader'],
  7. },
  8. ],
  9. },
  10. };

js文件里import css文件
build

使用 webpack-dev-server

安装

  1. yarn add webpack-dev-server --dev

webpack.config.js添加

  1. devServer: {
  2. contentBase: './dist',
  3. },

package.json添加scripts

  1. "scripts": {
  2. "start": "webpack-dev-server --open", // --open是自动打开浏览器,可去掉
  3. },

运行

  1. yarn start
  2. # 或者
  3. npm run start

yarn start不会生成dist文件夹,而是直接在内存里

生成CSS文件

安装mini-css-extract-plugin

  1. yarn add mini-css-extract-plugin --dev

webpack.config.js添加

  1. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  2. module.exports = {
  3. plugins: [
  4. new MiniCssExtractPlugin({
  5. // Options similar to the same options in webpackOptions.output
  6. // all options are optional
  7. filename: '[name].[contenthash].css',
  8. chunkFilename: '[id].[contenthash].css',
  9. ignoreOrder: false, // Enable to remove warnings about conflicting order
  10. }),
  11. ],
  12. module: {
  13. rules: [
  14. {
  15. test: /\.css$/,
  16. use: [
  17. {
  18. loader: MiniCssExtractPlugin.loader,
  19. options: {
  20. // you can specify a publicPath here
  21. // by default it uses publicPath in webpackOptions.output
  22. publicPath: '../',
  23. hmr: process.env.NODE_ENV === 'development',
  24. },
  25. },
  26. 'css-loader',
  27. ],
  28. },
  29. ],
  30. },
  31. };

development和production用不同配置

webpack.config.js

  1. const HtmlWebpackPlugin = require('html-webpack-plugin')
  2. const path = require('path');
  3. module.exports = {
  4. mode: 'development',
  5. entry: './src/index.js',
  6. output: {
  7. // path: path.resolve(__dirname, 'dist'),
  8. filename: '[name].[contenthash].js'
  9. },
  10. plugins: [
  11. new HtmlWebpackPlugin({
  12. title: 'Custom template',
  13. // Load a custom template (lodash by default)
  14. template: 'src/index.html'
  15. })
  16. ],
  17. module: {
  18. rules: [
  19. {
  20. test: /\.css$/,
  21. use: ['style-loader', 'css-loader']
  22. },
  23. ],
  24. },
  25. devServer: {
  26. contentBase: './dist',
  27. }
  28. };

webpack.config.prod.js

  1. const HtmlWebpackPlugin = require('html-webpack-plugin')
  2. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  3. const path = require('path');
  4. module.exports = {
  5. mode: 'production',
  6. entry: './src/index.js',
  7. output: {
  8. // path: path.resolve(__dirname, 'dist'),
  9. filename: '[name].[contenthash].js'
  10. },
  11. plugins: [
  12. new HtmlWebpackPlugin({
  13. title: 'Custom template',
  14. // Load a custom template (lodash by default)
  15. template: 'src/index.html'
  16. }),
  17. new MiniCssExtractPlugin({
  18. // Options similar to the same options in webpackOptions.output
  19. // all options are optional
  20. filename: '[name].[contenthash].css',
  21. chunkFilename: '[id].[contenthash].css',
  22. ignoreOrder: false, // Enable to remove warnings about conflicting order
  23. }),
  24. ],
  25. module: {
  26. rules: [
  27. {
  28. test: /\.css$/,
  29. use: [
  30. {
  31. loader: MiniCssExtractPlugin.loader,
  32. options: {
  33. // you can specify a publicPath here
  34. // by default it uses publicPath in webpackOptions.output
  35. publicPath: '../',
  36. hmr: process.env.NODE_ENV === 'production',
  37. },
  38. },
  39. 'css-loader',
  40. ],
  41. },
  42. ],
  43. },
  44. devServer: {
  45. contentBase: './dist',
  46. }
  47. };

package.json
start默认配置文件,build指定配置文件为prod

  1. "scripts": {
  2. "start": "webpack-dev-server",
  3. "build": "rm -rf dist && webpack --config webpack.config.prod.js",
  4. },

使用继承

webpack.config.base.js

  1. const HtmlWebpackPlugin = require('html-webpack-plugin')
  2. const path = require('path');
  3. module.exports = {
  4. mode: 'development',
  5. entry: './src/index.js',
  6. output: {
  7. // path: path.resolve(__dirname, 'dist'),
  8. filename: '[name].[contenthash].js'
  9. },
  10. plugins: [
  11. new HtmlWebpackPlugin({
  12. title: 'Custom template',
  13. // Load a custom template (lodash by default)
  14. template: 'src/index.html'
  15. })
  16. ],
  17. };

webpack.config.js

  1. const HtmlWebpackPlugin = require('html-webpack-plugin')
  2. const path = require('path');
  3. const base = require('./webpack.config.base') // 引入共有属性
  4. module.exports = {
  5. ...base, // 解构
  6. mode: 'development',
  7. module: {
  8. rules: [
  9. {
  10. test: /\.css$/,
  11. use: ['style-loader', 'css-loader']
  12. },
  13. ],
  14. },
  15. devtool: "inline-source-map",
  16. devServer: {
  17. contentBase: './dist',
  18. }
  19. };

webpack.config.prod.js

  1. const HtmlWebpackPlugin = require('html-webpack-plugin')
  2. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  3. const path = require('path');
  4. const base = require('./webpack.config.base')
  5. module.exports = {
  6. ...base,
  7. mode: 'production',
  8. plugins: [
  9. ...base.plugins,
  10. new MiniCssExtractPlugin({
  11. // Options similar to the same options in webpackOptions.output
  12. // all options are optional
  13. filename: '[name].[contenthash].css',
  14. chunkFilename: '[id].[contenthash].css',
  15. ignoreOrder: false, // Enable to remove warnings about conflicting order
  16. }),
  17. ],
  18. module: {
  19. rules: [
  20. {
  21. test: /\.css$/,
  22. use: [
  23. {
  24. loader: MiniCssExtractPlugin.loader,
  25. options: {
  26. // you can specify a publicPath here
  27. // by default it uses publicPath in webpackOptions.output
  28. publicPath: '../',
  29. hmr: process.env.NODE_ENV === 'production',
  30. },
  31. },
  32. 'css-loader',
  33. ],
  34. },
  35. ],
  36. }
  37. };

也可以使用merge方法,自行搜索

总结

webpack 的作用包括:

  1. 将一个或多个 JS 文件打包成对应的文件
  2. 将一个或多个 CSS 文件打包成对应的文件
  3. 压缩代码
  4. 将高版本的 JS转译成低版本的 JS