Commit cfd60804 authored by Jason Miller's avatar Jason Miller Committed by Joe Haddad

Feature: Add transparent JSX optimization (#8350)

* Add transparent JSX optimization.

* fix duplicate React import

* fix React not being imported when only a single Fragment node is present in a source module

* remove babel-plugin-react-require

* Fix JSX optimization for CommonJS source files.
parent 771c0b45
import { PluginObj } from '@babel/core'
import { NodePath } from '@babel/traverse'
import * as BabelTypes from '@babel/types'
export default function({
types: t,
}: {
types: typeof BabelTypes
}): PluginObj<any> {
return {
inherits: require('babel-plugin-syntax-jsx'),
visitor: {
JSXElement(path, state) {
state.set('jsx', true)
},
// Fragment syntax is still JSX since it compiles to createElement(),
// but JSXFragment is not a JSXElement
JSXFragment(path, state) {
state.set('jsx', true)
},
Program: {
exit(path: NodePath<BabelTypes.Program>, state) {
if (state.get('jsx')) {
const pragma = t.identifier(state.opts.pragma)
let importAs = pragma
// if there's already a React in scope, use that instead of adding an import
const existingBinding =
state.opts.reuseImport !== false &&
state.opts.importAs &&
path.scope.getBinding(state.opts.importAs)
// var _jsx = _pragma.createElement;
if (state.opts.property) {
if (state.opts.importAs) {
importAs = t.identifier(state.opts.importAs)
} else {
importAs = path.scope.generateUidIdentifier('pragma')
}
const mapping = t.variableDeclaration('var', [
t.variableDeclarator(
pragma,
t.memberExpression(
importAs,
t.identifier(state.opts.property)
)
),
])
// if the React binding came from a require('react'),
// make sure that our usage comes after it.
if (
existingBinding &&
t.isVariableDeclarator(existingBinding.path.node) &&
t.isCallExpression(existingBinding.path.node.init) &&
t.isIdentifier(existingBinding.path.node.init.callee) &&
existingBinding.path.node.init.callee.name === 'require'
) {
existingBinding.path.parentPath.insertAfter(mapping)
} else {
// @ts-ignore
path.unshiftContainer('body', mapping)
}
}
if (!existingBinding) {
const importSpecifier = t.importDeclaration(
[
state.opts.import
? // import { $import as _pragma } from '$module'
t.importSpecifier(
importAs,
t.identifier(state.opts.import)
)
: state.opts.importNamespace
? t.importNamespaceSpecifier(importAs)
: // import _pragma from '$module'
t.importDefaultSpecifier(importAs),
],
t.stringLiteral(state.opts.module || 'react')
)
// @ts-ignore
path.unshiftContainer('body', importSpecifier)
}
}
},
},
},
}
}
......@@ -97,13 +97,25 @@ module.exports = (
// This adds @babel/plugin-transform-react-jsx-source and
// @babel/plugin-transform-react-jsx-self automatically in development
development: isDevelopment || isTest,
pragma: '__jsx',
...options['preset-react'],
},
],
require('@babel/preset-typescript'),
],
plugins: [
require('babel-plugin-react-require'),
[
require('./plugins/jsx-pragma'),
{
// This produces the following injected import for modules containing JSX:
// import React from 'react';
// var __jsx = React.createElement;
module: 'react',
importAs: 'React',
pragma: '__jsx',
property: 'createElement',
},
],
require('@babel/plugin-syntax-dynamic-import'),
require('./plugins/react-loadable-plugin'),
[
......
......@@ -72,7 +72,6 @@
"autodll-webpack-plugin": "0.4.2",
"babel-core": "7.0.0-bridge.0",
"babel-loader": "8.0.6",
"babel-plugin-react-require": "3.0.0",
"babel-plugin-transform-define": "1.3.1",
"babel-plugin-transform-react-remove-prop-types": "0.4.24",
"chalk": "2.4.2",
......
/* eslint-env jest */
import { transform } from '@babel/core'
const trim = s =>
s
.join('\n')
.trim()
.replace(/^\s+/gm, '')
// avoid generating __source annotations in JSX during testing:
const NODE_ENV = process.env.NODE_ENV
process.env.NODE_ENV = 'production'
const preset = require('next/dist/build/babel/preset')
process.env.NODE_ENV = NODE_ENV
const babel = (code, esm = false) =>
transform(code, {
filename: 'noop.js',
presets: [preset],
babelrc: false,
configFile: false,
sourceType: 'module',
compact: true,
caller: {
name: 'tests',
supportsStaticESM: esm
}
}).code
describe('next/babel', () => {
it('should transform JSX to use a local identifier in modern mode', () => {
const output = babel(`const a = () => <a href="/">home</a>;`, true)
// it should add a React import:
expect(output).toMatch(`import React from"react"`)
// it should hoist JSX factory to a module level variable:
expect(output).toMatch(`var __jsx=React.createElement`)
// it should use that factory for all JSX:
expect(output).toMatch(`__jsx("a",{href:"/"`)
expect(
babel(`const a = ()=><a href="/">home</a>`, true)
).toMatchInlineSnapshot(
`"import React from\\"react\\";var __jsx=React.createElement;var a=function a(){return __jsx(\\"a\\",{href:\\"/\\"},\\"home\\");};"`
)
})
it('should transform JSX to use a local identifier in CommonJS mode', () => {
const output = babel(trim`
const a = () => <React.Fragment><a href="/">home</a></React.Fragment>;
`)
// Grab generated names from the compiled output.
// It looks something like this:
// var _react = _interopRequireDefault(require("react"));
// var __jsx = _react["default"].createElement;
// react: _react
// reactNamespace: _react["default"]
const [, react, reactNamespace] = output.match(
/(([a-z0-9_]+)(\[[^\]]*?\]|\.[a-z0-9_]+)*?)\.Fragment/i
)
expect(output).toMatch(`var ${reactNamespace}=`)
expect(output).toMatch(`require("react")`)
expect(output).toMatch(`var __jsx=${react}.createElement`)
// Fragment should use the same React namespace import:
expect(output).toMatch(`__jsx(${react}.Fragment`)
expect(output).toMatch(`__jsx("a",{href:"/"`)
expect(babel(`const a = ()=><a href="/">home</a>`)).toMatchInlineSnapshot(
`"\\"use strict\\";var _interopRequireDefault=require(\\"@babel/runtime-corejs2/helpers/interopRequireDefault\\");var _react=_interopRequireDefault(require(\\"react\\"));var __jsx=_react[\\"default\\"].createElement;var a=function a(){return __jsx(\\"a\\",{href:\\"/\\"},\\"home\\");};"`
)
})
it('should support Fragment syntax', () => {
const output = babel(`const a = () => <>hello</>;`, true)
expect(output).toMatch(`React.Fragment`)
expect(babel(`const a = () => <>hello</>;`, true)).toMatchInlineSnapshot(
`"import React from\\"react\\";var __jsx=React.createElement;var a=function a(){return __jsx(React.Fragment,null,\\"hello\\");};"`
)
})
it('should support commonjs', () => {
const output = babel(
trim`
const React = require('react');
module.exports = () => <div>test2</div>;
`,
true
)
expect(output).toMatchInlineSnapshot(
`"var React=require('react');var __jsx=React.createElement;module.exports=function(){return __jsx(\\"div\\",null,\\"test2\\");};"`
)
})
})
......@@ -3204,11 +3204,6 @@ babel-plugin-jest-hoist@^24.6.0:
dependencies:
"@types/babel__traverse" "^7.0.6"
babel-plugin-react-require@3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/babel-plugin-react-require/-/babel-plugin-react-require-3.0.0.tgz#2e4e7b4496b93a654a1c80042276de4e4eeb20e3"
integrity sha1-Lk57RJa5OmVKHIAEInbeTk7rIOM=
babel-plugin-syntax-jsx@6.18.0:
version "6.18.0"
resolved "https://registry.yarnpkg.com/babel-plugin-syntax-jsx/-/babel-plugin-syntax-jsx-6.18.0.tgz#0af32a9a6e13ca7a3fd5069e62d7b0f58d0d8946"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment