Vite3.0 发布

Vite 是基于原生 ESM 模块的新一代开发与构建工具。

使用

Vite 能够帮助你快速创建一个应用,它内置了多种模板.在线体验 Vite

> npm create vite@latest

首次启动 vite 时,会执行 依赖预构建,会非常慢,因此不要随便停止 Vite

Vite 3 相对于 Vite2 的变化

官方 changelog 在这里,总体来是修复了 400+ issuse,减少了包体积,以及冷启动得到优化.

用法可以理解为:木得变化

关于 ESM 模块化

ESM 是一个模块化方案,ecma 委员会于2015.6 发布后成为 ECMA(Javascript)标准.

随后各个浏览器厂商开始准备开发工作,跟进此标准,在 2018 年 5 月 Firefox 60 发布后,所有的主流浏览器就都默认支持 ESM 了。

Node 也正在添加 ESM 支持,为此还成立了工作小组来专门研究 CJS 和 ESM 之间的兼容性问题。

所以,在 2022 年你已经可以直接在 <script> 标签中使用 type=“module”,并且在代码中使用 importexport 来引入第三方库

<script type="module">
  import {
    
     html, Component, render } from 'https://unpkg.com/htm/preact/standalone.module.js';
  class App extends Component {
    
    
    state = {
    
    
      count: 0
    }
    add = () => {
    
    
      this.setState({
    
     count: this.state.count + 1 });
    }
    render() {
    
    
      return html`
        <div class="app">
          <div>count: ${
      
      this.state.count}</div>
          <button onClick=${
      
      this.add}>Add Todo</button>
        </div>
      `;
    }
  }
  render(html`<${
      
      App} page="All" />`, document.body);
</script>

  • 在 Vite 流行起来之前,为什么大家伙儿没有使用 ESM 模块化方案, 而是采用 CommonJS、AMD 这两种模块化方案呢?

  • 因为你看上面写的历史啊,主流浏览器都支持 ESM 模块化也就是 2018.5 月起,用户还不会及时更新自己的浏览器到最新版本,而 Vite 也是 2019 年才出现的。

  • 所以 3 年(发展)过去了,http2 普及了,目前已经可以无忧的使用 ESM 方案, 也就是可以无忧使用 Vite 。

现有模块标准

3 种标准目的是一样的,都是模块化,只是各自定义了各自的写法。

  1. CommonJS 只适用于 node 端:
const lodash = require("lodash");

module.exports = function doSomething(n) {
    
    
  console.log(lodash);
};
  1. AMD 只适用于浏览器端:
define(["dep1", "dep2"], function (dep1, dep2) {
    
    
  return function () {
    
    };
});
  1. UMD 代表通用模块定义(Universal Module Definition):
(function (root, factory) {
    
    
  if (typeof define === "function" && define.amd) {
    
    
    // AMD. Register as an anonymous module.
    define([], factory);
  } else if (typeof module === "object" && module.exports) {
    
    
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    
    
    // Browser globals (root is window)
    root.returnExports = factory();
  }
})(typeof self !== "undefined" ? self : this, function () {
    
    
  // Just return a value to define the module export.
  // This example returns an object, but the module
  // can return a function as the exported value.
  return {
    
    };
});

拓展阅读

Vite 中文官方文档
Javascript 模块化历史
ECMAScript Modules

猜你喜欢

转载自blog.csdn.net/win7583362/article/details/125804572