webpack

  • npm install webpack webpack-cli --global. 全局安装

  • yarn add webpack-dev-server -D

    • -D 开发依赖
    • -S 生产依赖 Lodash
  • 不建议全局安装

    本地安装步骤

    • 初始化创建package.json文件 : npm init -y/yarn init -y
    • 安装webpack: npm install /yarn add webpack webpack-cli -D
    • 打包html: yarn add html-webpack-plugin -D
    • webpack --stats details 详细的打包情况
    • npm view webpack-cli version 查看版本
    • npx webpack --help 查看帮助
    • Plugin :插件是类或者构造函数,使用时需要实例化
    配置html-webpack-plugin
      const HtmlWebpackPlugin  = require("html-webpack-plugin") 
      
       plugins: [
          new HtmlWebpackPlugin({
            // 设置模板源 (一般不设置)
            template: './public/index.html',
            // 设置文件名(一般不设置)
            filename: 'index.html',
            // 保留页面中的内容
            inject: true
          })
        ],
    
  • npx webpack --entry ./src/index.js --mode production设置入口 生产模式 打包到dist文件夹中

  • path 要设置绝对路径. path : path.resolve(__dirname,’./dist’)

    • 自动生成html入口文件和引用js文件

在这里插入图片描述

  • 清理dist clean:true

  • npx webpack --watch自动监听变化

  • webpack-dev-server 检测变化,实现自动刷新

    • npm install webpack-dev-server -D 搭建开发环境
    • npx webpack-dev-server

    配置脚本

      "scripts": {
          "dev"  : "npx webpack-dev-server",
          "build": "npx webpack"
        },
    

    配置dev

     devServer: {
        contentBase: path.resolve(__dirname,'./dist'),
        port: 8080
      }
    

    出口

      const path = require('path');
      module.exports = {
        // 入口文件(可以设置多个,使用数组,或者对象,对象可以取别名即可)
        entry: './src/main.js',
        // 出口
        output:{
          // 生成的路径  必须是绝对路径(引入path模块)
          path: path.resolve(__dirname,'./dist'),
          // 生成的文件名, 设置hash,:5代表5位([contenthash:5])
          filename: '[name]-[contenthash:5].js'
        }
      }
    

    node cross-env

    • cross-env 可以在配置脚本中,向配置文件中传入参数,从而可以做到不同的脚本执行同一配置文件

      "script" : {
        "dev" :"cross-env NODE_ENV=development npx webpack-dev-server --config ./src/config/webpack.config.dev.js",
        "build":"cross-env NODE_ENV=production npx w"
      }
      
  • 资源模块

    • asset module type
      • asset/resource
        • 发送单独文件并导出url
      • asset/inline
        • 导出一个资源的Data URL
        • Data URl是一个很巧妙的将图片嵌入Html的方法,图片被转换成base64编码的字符串形式,并储存在URL中
      • asset/source 源代码
        • 通用资源源代码
      • asset. 导出一个Data URL
        • 通用资源类型
  • npx webpack-dev-server --open 自动启动文件

  • assetModuleFilename : 'images/[contenthash][ext]'哈希

loader

module.exports ={
   module : {
     rules : [{
       test : /\.txt$/ ,
       use : 'raw-loader'
      ]
    }
 ]
  • test :识别出哪些文件被转换
  • use:应该使用哪个loader来转换
  • 安装css-loader
  • npm install css-loader -D
  • npm install style-loader -D
  • npm install less-loader -D
  • npm install mini-css-extract-plugin -D
  • npm install css-minimizer-webpack-plugin -D
  • npm install csv-loader xml-loader -D
  • data.xml会转化成一个js对象
  • data.csv会转化成一个数组

parse

  • data.yaml
  • toml
  • json5
  • npm install yaml toml json5 -D

babel-loader

  • es6转为es5
  • babel-loader:在webpack里应用babel解析ES6的桥梁
  • @babel/core: babel 核心模块
  • @babel/preset-env: bable预设,一组babel插件的集合
  • npm install babel-loader @babel/core @babel/preset-env -D
  • regeneratorRuntime是webpack打包生产的全局辅助函数,由babel生产,用于兼容async/await的语法
  • npm install @babel/runtime -D
  • npm install @babel/plugin-transform-runtime -D

代码分离

  • 入口起点

    • 使用entry配置手动分离代码
  • 防止重复

    • 使用Entry dependencies 或者SplitChunksPlugin 去重和分离代码
  • 动态导入

    • 通过模块的内联函数调用来分离代码
  • splitChunks :代码分割

    •  splitChunks : {
              chunks : 'all ' //代码分割
          }
      

-在这里插入图片描述
懒加载

  • preload预加载
  • ​ publicPath :‘http://localhost:8000/’ //项目前端域名,cdn域名 公共路径

环境变量 --env

  • npx webpack --env production 生产环境打包

    module.export = (env) =>{
    
    mode : env.production ? production :development
    }
    
  • 打包插件 terser

    • npm install terser-webpack-plugin

拆分配置

  • 开发环境

    • npx webpack -c ./config/webpack.config.dev.js. 指定文件
  • 生产环境

    • npx webpack -c ./config/webpack.config.prod.js
  • npx webpack serve -c ./config/webpack.config.dev.js

    performance : {
      hints:false //关闭性能方面的提示 
    }
    

提取公共配置

  • merge 包

    • npm install webpack-merge -D
    const { merge } =require('webpack-merge')
    
    const commmonConfig = require('./webpack.config.common')
    const productionConfig = require('./webpack.config.prod')
    const developmentConfig = require('./webpack.config.dev')
    
    module.exports =  (env) => {
        switch(true){
            case env.development :
              return merge(commmonConfig,developmentConfig)
            case env.production :
              return merge(commmonConfig,productionConfig)
    
            default:
                return new Error('No matching configuration was found')
        }
    }
    

Source-map

生产环境不适用

在这里插入图片描述

  • eval
  • source-map
  • hidden-source-map
  • inline-source-map
  • eval-source-map
  • cheap-source-map
  • cheap-module-source-map 推荐使用

devserve

  devServer : {
        static :path.resolve(__dirname,'./dist'),
        compress : true , //是不是在服务器端进行代码压缩,使之可以减少传输数据的大小,提高传输效率,
        port : '3000' ,// 服务端口号
        host : '0.0.0.0' ,
        headers : {
          'X-Access-Token' : 'sss' //自定义请求头
        },
        proxy : {
           '/api' : 'http://localhost:9000'
        },
        // https : true
        http2 : true ,//自带证书 
        historyApiFallback : true  //路由跳到根页面 
        hot :true  //
        liveReload : true  
    },
  • 开发服务器主机 host : ‘0.0.0.0’ ,
  • 大大提高调试效率
    • 模块热替换 : hot :true
    • 热加载 liveReload : true

Eslint

  • npm install eslint -D
  • npx eslint --init
  • npx eslint 指定命令来检查错误

在这里插入图片描述

外部扩展

  • 为了减少外部体积,从而把第三方库用cdn的形式引入进来

  • 方法一

    • webpack.config.js

       plugins :[
              new HtmlWebpackPlugin({
                   template : './index.html'
               })
                externals : {
              jquery : 'jQuery'
          }
          ],
      
    • 创建html文件,引入外部链接

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Document</title>
          <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
      </head>
      <body>
          
      </body>
      </html>
      
  • 方法二

    • 直接把链接放在webpack配置中,

    • const path =require( 'path')
      const HtmlWebpackPlugin =require('html-webpack-plugin')
      
      module.exports = {
          mode : 'development' ,
          entry : './app.js',
      
          plugins :[
          
               new HtmlWebpackPlugin()
      
          ],
          externalsType : 'script' ,
          externals : {
              jquery : [
                      'https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js',
                  '$'
              ]
             
          }
        
      }
      

依赖图

  • npm i lodash -S

  • npm install webpack-bundle-analyzer -D

PostCSS 与 CSS模块

  • postCSS是一个用javascript工具和插件转换css代码的工具,讲最新的css语法转换为大多数浏览器都能理解的语法

  • npm i posts-loader -D

  • npm i autoprefixer -D 加载样式前缀

  • 浏览器版本设置

    • 在根目录创建browserlist文件夹

    • 在package.json 中 配置browserlist

       "browserslist" : [
           "> 1%" , //全球应用率大于 1%
           "last 2 versions" //最近的两个版本
         ]
      
  • npm install posts-nested -D. 可以在样式里写嵌套

Web Works

在这里插入图片描述

TypeScript

  • npm i typescript ts-loader -D

  • npx tsc --init

  • npm i @types/lodash --save-dev

多页面

plugins :[
      new HtmlWebpackPlugin({
        title : '多页面应用' ,
        template :'./index.html',
        inject :'body',
        chunks : [ 'main' , 'main2' , 'lodash']
      })
  ]
    <title> <%= htmlWebpackPlugin.options.title %> </title>

PWA 渐进式网络应用程序

  • npm i http-server -D

  • package.json中的scripts配置。 “start”: “http-server dist”,

  • npm i workbox-webpack-plugin -D

  • s

    const HtmlWebpackPlugin =require('html-webpack-plugin')
    const WorkboxPlugin = require('workbox-webpack-plugin')
    module.exports = {
    
      mode :'development' ,
    
      entry : './src/index.js' ,
      plugins  :[
        new HtmlWebpackPlugin(),
        new WorkboxPlugin.GenerateSW ({
          clientsClaim : true , //快速启用work servers
          skipWaiting :true  //跳出等待 ,不允许留下旧的servers-works
        })
      ],
      devServer : {
        devMiddleware : {
          writeToDisk : true
        }
      } 
    }
    

shimming 预置依赖

在这里插入图片描述

  • npm i export-loader -D
  • polyfill

polyfill

  • npm i @babel/polyfill
  • mylib

发布包

  • https://www.npmjs.com/
  • 注册账号
  • npm config get registry
  • npm adduser
  • npm publish

提升构建性能

通用环境
  • 更新到最新版本

  • 将loader 应用于最少数量的必要模块

  • 引导bootstrap

    • 每个额外的loader/plugin都有启动时间,尽量少的使用工具
  • 解析

    • 配置resolve来提高解析速度

      • 减少resolve.modules,resolve.extensions,resolve.mainFile,resolve.descriptFiles中条目数量,因为他们会增加文件系统调用的次数
      • 如果你不适用symlinks(例如npm link 活yarn link),可以设置resolve.symlinks:false
      • 如果你使用resolve plugin 规则,并且没有指定context 上下文,可以设置resolve.cacheWithContext:false
  • 小就是快

    • 减少编译结果的整体大小,以提高构建性能,尽量保持chunk体积小

      • 使用数量更小/体积更小的library
      • 在多页面应用程序中使用SplitChunkPlugin
      • 在多页面应用程序中使用SplitChunksPlugin,并开启async模式
      • 移除未引用代码
      • 只编译你当前正在开发的那些代码
  • 持久化缓存

    • 在webpack配置中使用cache选项,使用package.json中的 'postinstall’清除缓存目录

    • 讲cache类型设置为内存或者文件系统,memory选项告诉webpac在内存中存储缓存,不允许额外的配置

      module.exports = {
        cache : {
           type : 'memory'
        }
      }
      
  • 自定义plugin/loader

    • 将他们进行概要分析,以免在此处引入性能问题
  • Progress plugin

    • 将ProgressPlugin从webpack 中删除,可以缩短构建时间,但是可能不会为快速构建提供太多价值
  • dll

    • 使用DllPlugin为更改不频繁的代码生成单独的编译结果,可以提高应用程序的编译速度,但是他增加了构建过层的复杂度
  • worker 池

    • Thread-loader 可以将非常消耗资源的loader分流给一个worker poll
开发环境
  • 增量编译

    • 使用webpack 的watch mode (监听模式),不适用其他工具
    • 在某些配置中,watch mode会退回到poll mode 轮询模式,可以使用watchOptions.poll来增加轮询的间隔时间
  • 在内存中编译

    • 通过在内存中而不是写入磁盘编译和serve资源来提高性能
    • webpack-dev-server
    • webpack-hot-middleware
    • webpack-dev-middleware
  • stats.toJson加速

  • Devtool

    • Eval具有最好的性能,但不能帮你转译代码
    • Cheap-source-map变体配置来提高性能,但是map质量差一点
    • 使用eval-source-map 变体配置进行增量编译
    • 大多情况下最佳选择eval-cheap-module-source-map
  • 避免在生产环境才使用到的工具

    • Utility,plugin,loader只用于生产环境
    • TerserPlugin
    • [fullhash]/[chunkhash]/[contenthash]
    • AggressiveSplityingPlugin
    • AggressiveMergingPlugin
    • ModuleConcatenationPlugin
  • 最小化entry chunk

    • 确保在生成entry chunk时,尽量减少体积来提高性能

      module.exports = {
        optimization : {
          runtimeChunk : true
        }
      }                           
      
  • 避免额外的优化步骤

    • 有些优化适用于小型代码库,在大型中非常耗性能

      module.exports = {
         optimization : {
         removeAvailableModules :false,
         removeEmptyChunks :false ,
         splitChunks :false ,
         }
      }	
      
  • 输出结果不携带路径信息

    • webpack会在输出的bundle中生成路径信息,会导致造成垃圾回收性能压力

      module.exports= {
        output :{
          pathinfo :false
        }
      }
      
  • Node.js版本问题

    • 8.9.10-9.11.1中ES5Mao和Set实现存在性能回退
  • ts loader

在这里插入图片描述

生产环境
  • 不启用source-map

具体步骤

  • npm init -y

  • npm install webpack webpack-cli webpack-dev-server html-webpack-plugin -D

  • npm install babel-loader @babel/core @babel/preset-env -D

  • npm install style-loader css-loader -D

  • npx webpack

  • npx webpack server --open

  • “sideEffects” : false, //所有的包都没有副作用

  • “sideEffects” : [ “*.css”]. //看的css就不要做删除了,是有副作用的

  • data-main 入口

  • require.js

  • type=module. 模块化

  • rollup.js

  • vite 基于esmodule

  • petite Vue

  • pwd。打印当前目录,以绝对路径的方式显示用户当前的工作目录

    git

  • git --version

  • git init

  • 创建.gitignore文件。**/node_modules

  • ls -la

  • git status

  • touch pre-commit

  • vim pre-commit

  • chmod +x ./pre-commit. 给pre-commit添加可执行权限

  • cd .git

  • cd hooks

  • vim pre-commit

  • 创建新文件夹.mygithooks 新文件pre-commmit

  • git config core.hookPath .mygithooks

  • cd .git

  • cat config

  • chmod +x .mygithooks/pre-commit

  • husky

    • npm install husky -D
    • npx husky install
  • 模块

    • resolve : {
        alias : {
         "@" : path.resolve(_dirname , './src')
        },
          extensions : ['.json' , '.js' ,'.vue'] //扩展名 ,查找顺序按照从前向后顺序找
      
      }
      
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值