Commit 330bedac authored by Joe Haddad's avatar Joe Haddad Committed by Tim Neutkens

Add Babel plugin that fixes className for Amp elements (#6486)

This is a simple Babel plugin that overwrites certain attributes for `amp-` elements.
parent a8d7a6ce
import { PluginObj } from '@babel/core'
import { NodePath } from '@babel/traverse'
import { JSXOpeningElement } from '@babel/types'
export default function AmpAttributePatcher(...args: any): PluginObj {
return {
visitor: {
JSXOpeningElement(path: NodePath<JSXOpeningElement>) {
const openingElement = path.node
const { name, attributes } = openingElement
if (!(name && name.type === 'JSXIdentifier')) {
return
}
if (!name.name.startsWith('amp-')) {
return
}
for (const attribute of attributes) {
if (attribute.type !== 'JSXAttribute') {
continue
}
if (attribute.name.name === 'className') {
attribute.name.name = 'class'
}
}
},
},
}
}
...@@ -78,6 +78,7 @@ module.exports = (context: any, options: NextBabelPresetOptions = {}): BabelPres ...@@ -78,6 +78,7 @@ module.exports = (context: any, options: NextBabelPresetOptions = {}): BabelPres
...options['transform-runtime'] ...options['transform-runtime']
}], }],
[require('styled-jsx/babel'), styledJsxOptions(options['styled-jsx'])], [require('styled-jsx/babel'), styledJsxOptions(options['styled-jsx'])],
require('./plugins/amp-attributes'),
isProduction && require('babel-plugin-transform-react-remove-prop-types') isProduction && require('babel-plugin-transform-react-remove-prop-types')
].filter(Boolean) ].filter(Boolean)
} }
......
export default () => 'Hello World' export default () => (
<amp-layout className='abc' layout='responsive' width='1' height='1'>
<span>Hello World</span>
</amp-layout>
)
...@@ -68,6 +68,9 @@ describe('AMP Usage', () => { ...@@ -68,6 +68,9 @@ describe('AMP Usage', () => {
const html = await renderViaHTTP(appPort, '/?amp=1') const html = await renderViaHTTP(appPort, '/?amp=1')
await validateAMP(html) await validateAMP(html)
expect(html).toMatch(/Hello World/) expect(html).toMatch(/Hello World/)
const $ = cheerio.load(html)
expect($('.abc').length === 1)
}) })
it('should add link preload for amp script', async () => { it('should add link preload for amp script', async () => {
......
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