获取了网站源码有什么用_【Vite 源码学习】2. Vite构建工具为什么用Rollup

3ace9efb77e7f7ffeb75bff32f4804cd.png
本文将会回答Vite为什么选择Rollup作为构建工具,为什么不用Rollup的热更新,以及为什么不用webpack。

一、Vite生产环境为什么选择Rollup做构建工具。

Vite是一个由原生ESM驱动的Web开发构建工具。在选择构建工具的时候也最好可以选择基于ESM的工具。

Rollup是基于ES2015的JavaScript打包工具。它将小文件打包成一个大文件或者更复杂的库和应用,打包既可用于浏览器和Node.js使用。 Rollup最显著的地方就是能让打包文件体积很小。相比其他JavaScript打包工具,Rollup总能打出更小,更快的包。因为Rollup基于ES2015模块,比Webpack和Browserify使用的CommonJS模块机制更高效。

二、Vite为什么不用Rollup的热更新

Vite开发模式单独实现了一套热更新(HMR - Hot Module Replacement),可是从Rollup Awesome中可以发现,Rollup有热更新插件nollup。为什么Vite不用Rollup的热更新呢?

从Vite的README,我们可以发现:

Vite was created to tackle native ESM-based HMR. When Vite was first released with working ESM-based HMR, there was no other project actively trying to bring native ESM based HMR to production.

也就是说Vite是第一个发布基于纯ESM的热更新。当时Rollup还没有纯ESM的热更新。

三、Vite为什么不用Webpack

Webpack和Rollup功能差不多,以前有种说法是应用开发用Webpack,库开发用Rollup。但是现在Webpack也支持Tree shaking,Rollup也有热更新,而且都有强大的插件开发功能。二者的功能差异越来越模糊。

二者更多的区别是在写法上。

如下是Rollup的配置文件:

// rollup.config.js
import babel from 'rollup-plugin-babel';

export default {
    input: './src/index.js',
    output: {
        file: './dist/bundle.rollup.js',
        format: 'cjs'
    },
    plugins: [
        babel({
            presets: [
                [
                    'es2015', {
                        modules: false
                    }
                ]
            ]
        })
    ]
}

下面是webpack的配置文件:

// webpack.config.js
const path = require('path');
const webpack = require('webpack');

module.exports = {
    entry: {
        'index.webpack': path.resolve('./src/index.js')
    },
    output: {
        libraryTarget: "umd",
        filename: "bundle.webpack.js",
    },
    module: {
        rules: [
            {
                test: /.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015']
                }
            }
        ]
    }
};

可以看出:

  • Rollup使用新的ESM,而Webpack用的是旧的CommonJS。
  • Rollup支持相对路径,webpack需要使用path模块。

Rollup使用起来更简洁,并且Rollup打出更小体积的文件,所以Rollup更适合Vite。

相关链接

上一篇:

Lee Wen:【Vite 源码学习】1. 环境搭建​zhuanlan.zhihu.com
66930cddf17a7c13fa99ee2cb7a2df65.png

下一篇:

Lee Wen:【Vite 源码学习】3. package.json分析​zhuanlan.zhihu.com
f258a43fd6186c7959add013ed8a7a59.png
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值