关于前端打包管理的一些概念

1. 更新包版本

yarn upgrade -latest @byted-edu/question-react-render

yarn add <package>@latest

yarn add <package>@version

2. 安装

yarn add <package>

// 安装开发依赖
yarn add <package> -D

// 发版本
yarn publsih --tag <tagname>

3. npx

主要特点:

1、临时安装可执行依赖包,不用全局安装,不用担心长期的污染。

2、可以执行依赖包中的命令,安装完成自动运行。

3、自动加载node_modules中依赖包,不用指定$PATH

4、可以指定node版本、命令的版本,解决了不同项目使用不同版本的命令的问题。

4. 打包压缩

  1. entry
  2. 防止重复
  3. 动态导入
  4. 预加载
  5. bundle分析
    1. webpack-bundle-analyzer

5.babel

将高版本es6+语法转低版本es5支持的code

  • 语法层:let、const。。。
    • Preset-env
  • API层:Promise,includes原型链上定义的新方法
    • Pollyfill

5.1 配置文件

// .babelrc
{
    presets: ["@babel/preset-env"]
}

5.2 pollyfill

使用pollyfill处理api层

但是并不想引入全量的垫片,所以

5.2.1 useBuiltIns

  • false:默认值,不操作pollyfill
  • entry:根据target中浏览器版本的支持,将pollyfills拆分引入,仅引入指定浏览器不支持API的pollyfill
  • usage:新,检测ES6/7/8等的使用情况,仅仅加载代码中用到的polyfills
{
  presets: [
    [
      '@babel/preset-env',
      {
        useBuiltIns: 'usage',
        corejs: 3,
      },
    ],
  ],
}

5.2.2 @babel/plugin-transform-runtime

  • 解决代码冗余,该插件会复用babel注入的辅助函数,这些辅助函数在@babel/runtime中,需增加该依赖yarn add @babel/runtime @babel/plugin-transform-runtime -D
{
  presets: [
    [
      '@babel/preset-env',
      {
        useBuiltIns: 'usage',
        corejs: 3,
      },
    ],
  ],
    plugins: [['@babel/plugin-transform-runtime']],
}
  • 解决全局污染

在文件头引入的core-js的pollyfill必然会导致全局污染,例如Array.from()等会修改全局对象的原型prototype

解决方式:将core-js给transform-runtime处理

{
  presets: [
    ['@babel/preset-env' ],
    plugins: [['@babel/plugin-transform-runtime', {
        'corejs': 3
    }]],
}

5.3 总结示例

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "usage",
        "targets": {
          "ie": 10
        }
      }
    ]
  ],
 "plugins": [
   [
     "@babel/plugin-transform-runtime",
     {
       "corejs": 3
     }
   ]
 ]
}
发表评论 / Comment

用心评论~


Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/blog.dyboy.cn/content/templates/dyblog/footer.php:56) in /www/wwwroot/blog.dyboy.cn/include/lib/view.php on line 23