webpack

工程化

从业务着手

简单的单页面应用使用gulp打包+ 同步工具实现开发全流程

从复杂度考虑

框架是服务于我们的项目,而不是去维护框架

从已知到未知去扩展

不同技术有不同的适应点

webpack

webpack文档

核心概念

  • 入口

  • 出口

  • loader

  • 插件

loader与插件的区别: loader帮助webpack处理他不能处理的文件,插件可以做更加复杂的任务。

模式/ 兼容性

webpack安装方式和使用方式

  1. 第一步创建一个npm项目 :npm init -y (使用默认选项快速配置)生成package.json

  2. 安装webpackyarn add webpack -webpack-cli -D

  3. ./node_modules/.bin/webpack -version == npx webpack -version package.json里定义script

    {
      "name": "test",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "build": "webpack", // 打包编译
        "watch": "webpac --watch" // 热编译
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "devDependencies": {
        "webpack": "^4.39.3",
        "webpack-cli": "^3.3.7"
      }
    }
    
    
  4. 入口和输出

    webpack的配置文件写在webpack.config.js

    1. 入口起点:
const config = {
	entry: "./src/index.js"
}
module.exports = config

终端里npm run build 执行webpack打包命令,从以上代码会将index.js作为入口打包,默认输出一个dist目录main.js文件

我们在很多时候很长的路径会使用一些简单的符号代替它,
nodejs里的path.join方法可以提供此类,__dirname当前项目目录名称
  1. loader顺序是从后往前:
  module: {
    rules: [
      {
        test: /\.css$/, use: [
          'style-loader',
          'css-loader' // 这里先
        ]
      },
      {test: /\.ts$/, use: 'ts-loader'}
    ]
  }

而当你想用预编译器比如:scss时候需要安装 yarn add sass node-sass -D 并且在webpack中添加rules

  module: {
    rules: [
      {
        test: /\.(scss|sass)$/, use: [
          'style-loader',
          'css-loader',
          'sass-loader'
        ]
      },
      {test: /\.ts$/, use: 'ts-loader'}
    ]
  }

loader如何去解决其他资源文件呢?

  1. 插件 plugins

    先安装对应的插件然后在plugins里引入

     var HtmlWebpackPlugin = require("html-webpack-plugin") 
     ...
    const config = {
      entry: "./src/index.js",
      output: {},
      module: {
        rules: [
      },
      plugins: [
          new HtmlWebpackPlugin()
      ]
    }
    module.exports = config
    

    由于插件可以携带参数/选项,你必须在 webpack 配置中,向 plugins 属性传入 new 实例。

对于HtmlWebpackPlugin来说,它会自动生成一个index.html,但是如果我们并不想让自己的html文件里的内容被清空的话需要我们自己在根目录下新建一个index.html,然后到new HtmlWebpackPlugin()里面添加参数

 new HtmlWebpackPlugin({
	 filename: "index.html", // 生成的新html文件名
	 template: "index.html" // 本地的html文件名,取得与webpack.config.js同级的文件
 })

这样生成新的html文件会将template作为原始html文件引入生成的js文件中

之前的编译手动,后来使用了webpack --watch来实现热编译,可以如何做到页面也能够热更新呢?vue-cli中就有如此功能,webpack 中的HMR就是提供这个功能的 .

如何使用?

yarn add webpack-de-server -D 安装,然后在package.json中的script添加"hot: "webpack-dev-server

var path = require("path")
+ var webpack = require("webpack") // 引入webpack
var HtmlWebpackPlugin = require("html-webpack-plugin") // 先安装,它会自动生成index.html引入生成的js 文件
const config = {
  entry: "./src/index.js",
  output: {
    path: path.join(__dirname, '/dist'),
    filename: "bundle.js"
  },
  module: {
    rules: [
      {
        test: /\.(scss|sass)$/, use: [
          'style-loader',
          'css-loader',
          'sass-loader'
        ]
      },
      {test: /\.ts$/, use: 'ts-loader'}
    ]
  },
  devServer: {
    hot: true
  },
  plugins: [
      new HtmlWebpackPlugin({
        filename: "index.html",
        template: "index.html"
      }),
    new webpack.HotModuleReplacementPlugin() // 插件里添加它
  ]
}

module.exports = config

同时在webpack.config.js中打开模块热替换的功能(以上备注的地方)

使用url-loader打包图片
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

const config = {
  entry: './src/index.js',
  output: {
    // path.join() 去拼接路径
    // __dirname 当前文件的绝对路径
    filename: 'bundle.js',
    path: path.join(__dirname, './dist')
  },
  module: {
    rules: [
      {
        // sass-loader node-sass两个依赖都需要安装
        test: /\.(scss|sass)$/,
        use: ['style-loader', 'css-loader', 'sass-loader']
      },
      {
        test: /\.(png|jpg|gif|otf)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 5102
            }
          }
        ]
      },
      {
        test: /\.html$/,
        use: [{
          loader: "html-loader",
          options: {
            minimize: true,
            removeComments: false,
            collapseWhitespace: false
          }
        }]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: "index.html",
      template: "work1.html"
    })
  ]
}

module.exports = config

字体文件需要file-loader,而在html文件中引入图片等需要使用html-loader

使用es6或者es7语法,且兼容低版本浏览器

开发环境

yarn add babel-loader @babel/core @babel/preset-env @babel/plugin-transform-runtime -D

生产环境

yarn add @babel/runtime -S

使用.babelrc进行配置简单的babel的设置

clean-webpack-plugin 去清楚构建文件夹

copy-webpack-plugin 去复制一些静态资源文件

    new CleanWebpackPlugin(), //每次build后清除dist
    new CopyWebpackPlugin([{ // 直接拷贝外层的资源文件不会去修改它
      from: path.join(__dirname,'assets'), // 从当前目录
      to: 'assets' // build后dist就会出现一个assets目录
    }]) // 拷贝静态资源,参数是一个数组

生产环境下需要对js和css文件进行压缩

TerserPluginminimizing

yarn add optimize-css-assets-webpack-plugin terser-webpack-plugin -D

yarn add mini-css-extract-plugin -D

MiniCssExtractPlugin

TerserPlugin

ok

总结

入口,出口,loader,插件,按需配置: 开发时热更新,生产时压缩,babel的配置

posted on 2019-09-05 19:38  2481  阅读(151)  评论(0编辑  收藏  举报

导航