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

This is a simple Babel plugin that overwrites certain attributes for `amp-` elements.
This commit is contained in:
Joe Haddad 2019-02-28 17:04:29 -05:00 committed by Tim Neutkens
parent a8d7a6ce42
commit 330bedacc7
4 changed files with 41 additions and 1 deletions

View file

@ -0,0 +1,32 @@
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'
}
}
},
},
}
}

View file

@ -78,6 +78,7 @@ module.exports = (context: any, options: NextBabelPresetOptions = {}): BabelPres
...options['transform-runtime']
}],
[require('styled-jsx/babel'), styledJsxOptions(options['styled-jsx'])],
require('./plugins/amp-attributes'),
isProduction && require('babel-plugin-transform-react-remove-prop-types')
].filter(Boolean)
}

View file

@ -1 +1,5 @@
export default () => 'Hello World'
export default () => (
<amp-layout className='abc' layout='responsive' width='1' height='1'>
<span>Hello World</span>
</amp-layout>
)

View file

@ -68,6 +68,9 @@ describe('AMP Usage', () => {
const html = await renderViaHTTP(appPort, '/?amp=1')
await validateAMP(html)
expect(html).toMatch(/Hello World/)
const $ = cheerio.load(html)
expect($('.abc').length === 1)
})
it('should add link preload for amp script', async () => {