Skip to content

Commit

Permalink
perf: use @babel/standalone + lazy load
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Jan 7, 2021
1 parent 7734105 commit b2f98fb
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 691 deletions.
18 changes: 12 additions & 6 deletions packages/plugin-legacy/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
// @ts-check
const path = require('path')
const babel = require('@babel/core')
const presetEnv = require('@babel/preset-env')
const { build } = require('vite')

// lazy load babel since it's not used during dev
let babel
/**
* @return {import('@babel/standalone')}
*/
const loadBabel = () => babel || (babel = require('@babel/standalone'))

// https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc
const safari10NoModuleFix = `!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",(function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()}),!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();`

Expand Down Expand Up @@ -177,18 +182,19 @@ function viteLegacyPlugin(options = {}) {

// transform the legacy chunk with @babel/preset-env
const sourceMaps = !!config.build.sourcemap
let { code, ast, map } = babel.transformSync(raw, {
let { code, ast, map } = loadBabel().transform(raw, {
ast: true,
configFile: false,
sourceMaps,
inputSourceMap: sourceMaps && chunk.map,
presets: [
[
presetEnv,
'env',
{
targets,
modules: false,
bugfixes: true,
loose: true,
useBuiltIns: needPolyfills ? 'usage' : false,
corejs: needPolyfills
? { version: 3, proposals: false }
Expand Down Expand Up @@ -324,12 +330,12 @@ function viteLegacyPlugin(options = {}) {
* @param {Set<string>} list
*/
function detectPolyfills(code, targets, list) {
const { ast } = babel.transformSync(code, {
const { ast } = loadBabel().transform(code, {
ast: true,
configFile: false,
presets: [
[
presetEnv,
'env',
{
targets,
modules: false,
Expand Down
3 changes: 1 addition & 2 deletions packages/plugin-legacy/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@
},
"homepage": "https://github.com/vitejs/vite/tree/main/packages/plugin-legacy#readme",
"dependencies": {
"@babel/core": "^7.12.10",
"@babel/preset-env": "^7.12.11",
"@babel/standalone": "^7.12.12",
"core-js": "^3.8.2",
"regenerator-runtime": "^0.13.7",
"systemjs": "^6.8.3"
Expand Down
Loading

0 comments on commit b2f98fb

Please sign in to comment.