Unverified Commit 62031ff2 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Move next-codemod to Next.js monorepo (#15536)

parent f4433cea
......@@ -8,4 +8,8 @@ packages/next/compiled/**/*
packages/react-refresh-utils/**/*.js
packages/react-dev-overlay/lib/**
**/__tmp__/**
.github/actions/next-stats-action/.work
\ No newline at end of file
.github/actions/next-stats-action/.work
packages/next-codemod/transforms/__testfixtures__/**/*
packages/next-codemod/transforms/__tests__/**/*
packages/next-codemod/**/*.js
packages/next-codemod/**/*.d.ts
......@@ -8,4 +8,8 @@ packages/react-refresh-utils/**/*.d.ts
packages/react-dev-overlay/lib/**
**/__tmp__/**
lerna.json
.github/actions/next-stats-action/.work
\ No newline at end of file
.github/actions/next-stats-action/.work
packages/next-codemod/transforms/__testfixtures__/**/*
packages/next-codemod/transforms/__tests__/**/*
packages/next-codemod/**/*.js
packages/next-codemod/**/*.d.ts
......@@ -3,3 +3,5 @@
**/dist/**
packages/next/compiled/**/*
lerna.json
packages/next-codemod/transforms/__testfixtures__/**/*
packages/next-codemod/transforms/__tests__/**/*
......@@ -13,7 +13,7 @@
"testsafari": "cross-env BROWSER_NAME=safari yarn testonly",
"testfirefox": "cross-env BROWSER_NAME=firefox yarn testonly",
"testie": "cross-env BROWSER_NAME=\"internet explorer\" yarn testonly",
"testall": "yarn run testonly -- --ci --forceExit",
"testall": "yarn run testonly -- --ci --forceExit && lerna run --scope @next/codemod test",
"genstats": "cross-env LOCAL_STATS=true node .github/actions/next-stats-action/src/index.js",
"pretest": "yarn run lint",
"git-reset": "git reset --hard HEAD",
......
*.d.ts
*.js
*.js.map
!transforms/__tests__/**/*.js
!transforms/__testfixtures__/**/*.js
\ No newline at end of file
# Next.js Codemod
This repository contains Codemod transformations to help upgrade Next.js codebases.
## v9
### `name-default-component`
Transforms anonymous components into named components to make sure they work with [Fast Refresh](https://nextjs.org/blog/next-9-4#fast-refresh).
For example
```jsx
// my-component.js
export default function () {
return <div>Hello World</div>
}
```
Transforms into:
```jsx
// my-component.js
export default function MyComponent() {
return <div>Hello World</div>
}
```
The component will have a camel cased name based on the name of the file, and it also works with arrow functions.
#### Usage
Go to your project
```
cd path-to-your-project/
```
Download the codemod:
```
curl -L https://github.com/zeit/next-codemod/archive/master.tar.gz | tar -xz --strip=2 next-codemod-master/transforms/name-default-component.js
```
Run the transformation:
```
npx jscodeshift -t ./name-default-component.js components/**/*.js
```
TypeScript files can use this codemod too:
```
npx jscodeshift -t ./name-default-component.js --parser=tsx components/**/*.tsx
```
If you have components in multiple folders, change the path to `**/*.js` and add `--ignore-pattern="**/node_modules/**"`.
After the transformation is done the `name-default-component.js` file in the root of your project can be removed.
### `withamp-to-config`
Transforms the `withAmp` HOC into Next.js 9 page configuration.
For example:
```js
// Before
import { withAmp } from 'next/amp'
function Home() {
return <h1>My AMP Page</h1>
}
export default withAmp(Home)
```
```js
// After
export default function Home() {
return <h1>My AMP Page</h1>
}
export const config = {
amp: true,
}
```
#### Usage
Go to your project
```
cd path-to-your-project/
```
Download the codemod:
```
curl -L https://github.com/zeit/next-codemod/archive/master.tar.gz | tar -xz --strip=2 next-codemod-master/transforms/withamp-to-config.js
```
Run the transformation:
```
npx jscodeshift -t ./withamp-to-config.js pages/**/*.js
```
After the transformation is done the `withamp-to-config.js` file in the root of your project can be removed.
## v6
### `url-to-withrouter`
Tranforms the deprecated automatically injected `url` property on top level pages to using `withRouter` and the `router` property it injects. Read more here: [err.sh/next.js/url-deprecated](https://err.sh/next.js/url-deprecated)
For example:
```js
// From
import React from 'react'
export default class extends React.Component {
render() {
const { pathname } = this.props.url
return <div>Current pathname: {pathname}</div>
}
}
```
```js
// To
import React from 'react'
import { withRouter } from 'next/router'
export default withRouter(
class extends React.Component {
render() {
const { pathname } = this.props.router
return <div>Current pathname: {pathname}</div>
}
}
)
```
This is just one case. All the cases that are transformed (and tested) can be found in the [`__testfixtures__` directory](./transforms/__testfixtures__/url-to-withrouter).
#### Usage
Go to your project
```
cd path-to-your-project/
```
Download the codemod:
```
curl -L https://github.com/zeit/next-codemod/archive/master.tar.gz | tar -xz --strip=2 next-codemod-master/transforms/url-to-withrouter.js
```
Run the transformation:
```
npx jscodeshift -t ./url-to-withrouter.js pages/**/*.js
```
After the transformation is done the `url-to-withrouter.js` file in the root of your project can be removed.
## Authors
- Tim Neutkens ([@timneutkens](https://twitter.com/timneutkens)) – [ZEIT](https://zeit.co)
- Joe Haddad ([@timer150](https://twitter.com/timer150)) - [ZEIT](https://zeit.co)
The MIT License (MIT)
Copyright (c) 2020 Vercel, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
{
"name": "@next/codemod",
"version": "1.1.0",
"license": "MIT",
"dependencies": {
"jscodeshift": "^0.6.4"
},
"scripts": {
"prepublish": "tsc -d -p tsconfig.json",
"build": "tsc -d -w -p tsconfig.json",
"test": "jest"
}
}
class ExistingName2Input {
render() {}
}
class nested {
render() {
const ExistingName2InputComponent = null;
}
}
export default () => <div>Anonymous function</div>;
class ExistingName2Input {
render() {}
}
class nested {
render() {
const ExistingName2InputComponent = null;
}
}
const ExistingName2InputComponent = () => <div>Anonymous function</div>;
export default ExistingName2InputComponent;
function ExistingName3Input() {}
function nested() {
const ExistingName3InputComponent = null;
}
export default () => <div>Anonymous function</div>;
function ExistingName3Input() {}
function nested() {
const ExistingName3InputComponent = null;
}
const ExistingName3InputComponent = () => <div>Anonymous function</div>;
export default ExistingName3InputComponent;
const ExistingNameIgnoreInput = null;
const ExistingNameIgnoreInputComponent = null;
export default () => <div>Anonymous function</div>;
const ExistingNameInput = null;
function nested() {
const ExistingNameInputComponent = null;
}
export default () => <div>Anonymous function</div>;
const ExistingNameInput = null;
function nested() {
const ExistingNameInputComponent = null;
}
const ExistingNameInputComponent = () => <div>Anonymous function</div>;
export default ExistingNameInputComponent;
const FunctionComponent2Input = () => <div>Anonymous function</div>;
export default FunctionComponent2Input;
export default () => {
const x = 'y';
if (true) {
return '';
}
return null;
};
export default () => {
const x = 'y';
if (true) {
return <div>Anonymous function</div>;
}
return null;
};
const FunctionComponentInput = () => {
const x = 'y';
if (true) {
return <div>Anonymous function</div>;
}
return null;
};
export default FunctionComponentInput;
export default function Name() {
const x = 'y';
if (true) {
return <div>Anonymous function</div>;
}
return null;
}
export default function () {
const x = 'y';
if (true) {
return <div>Anonymous function</div>;
}
return null;
}
export default function FunctionExpressionInput() {
const x = 'y';
if (true) {
return <div>Anonymous function</div>;
}
return null;
}
import {withRouter} from 'next/router'
export default withRouter(class extends React.Component {
render() {
const test = this.props.url
}
})
import {withRouter} from 'next/router'
export default withRouter(class extends React.Component {
render() {
const test = this.props.router
}
})
export default withAppContainer(withAuth(props => {
const test = props.url
}))
import { withRouter } from "next/router";
export default withRouter(withAppContainer(withAuth(props => {
const test = props.router
})));
\ No newline at end of file
export default class extends React.Component {
componentDidUpdate(prevProps) {
if (prevProps.url.query.f !== this.props.router.query.f) {
const test = this.props.url
}
}
}
import { withRouter } from "next/router";
export default withRouter(class extends React.Component {
componentDidUpdate(prevProps) {
if (prevProps.router.query.f !== this.props.router.query.f) {
const test = this.props.router
}
}
});
export default class extends React.Component {
componentWillReceiveProps(nextProps) {
if (this.props.url.query !== nextProps.url.query) {
const test = this.props.url
}
}
}
import { withRouter } from "next/router";
export default withRouter(class extends React.Component {
componentWillReceiveProps(nextProps) {
if (this.props.router.query !== nextProps.router.query) {
const test = this.props.router
}
}
});
export default class Something extends React.Component {
render() {
const {props, stats} = this
const test = props.url
}
}
import { withRouter } from "next/router";
export default withRouter(class Something extends React.Component {
render() {
const {props, stats} = this
const test = props.router
}
});
export default withAppContainer(
withAuth(
class BuyDomains extends React.Component {
render() {
const { url } = this.props
return (
<Page>
<Header
user={user}
pathname={url.pathname}
onLogout={() => {
onUser(null)
url.push('/login')
}}
onLogoRightClick={() => url.push('/logos')}
/>
</Page>
)
}
}
)
)
import { withRouter } from "next/router";
export default withRouter(withAppContainer(withAuth(
class BuyDomains extends React.Component {
render() {
const { router } = this.props
return (
<Page>
<Header
user={user}
pathname={router.pathname}
onLogout={() => {
onUser(null)
router.push('/login')
}}
onLogoRightClick={() => router.push('/logos')}
/>
</Page>
);
}
}
)));
\ No newline at end of file
class AddonsPage extends React.Component {
render() {
const {
url
} = this.props
return (
<Page>
<Header
user={user}
pathname={url.pathname}
onLogout={() => onUser(null)}
onLogoRightClick={() => Router.push('/logos')}
/>
<SubMenu
subscription={subscription}
teamsAndUser={teamsAndUser}
teams={teams}
user={user}
url={url}
/>
</Page>
)
}
}
export default withAppContainer(withAuthRequired(withError(AddonsPage)))
import { withRouter } from "next/router";
class AddonsPage extends React.Component {
render() {
const {
router
} = this.props
return (
<Page>
<Header
user={user}
pathname={router.pathname}
onLogout={() => onUser(null)}
onLogoRightClick={() => Router.push('/logos')}
/>
<SubMenu
subscription={subscription}
teamsAndUser={teamsAndUser}
teams={teams}
user={user}
url={router}
/>
</Page>
);
}
}
export default withRouter(withAppContainer(withAuthRequired(withError(AddonsPage))));
export default withApp(withAuth(class Something extends React.Component {
render() {
const {props, stats} = this
const test = props.url
}
}))
import { withRouter } from "next/router";
export default withRouter(withApp(withAuth(class Something extends React.Component {
render() {
const {props, stats} = this
const test = props.router
}
})));
\ No newline at end of file
class Test extends React.Component {
render() {
const test = this.props.url
}
}
export default wrappingFunction(Test)
import { withRouter } from "next/router";
class Test extends React.Component {
render() {
const test = this.props.router
}
}
export default withRouter(wrappingFunction(Test));
class Test extends React.Component {
render() {
const test = this.props.url
}
}
export default Test
import { withRouter } from "next/router";
class Test extends React.Component {
render() {
const test = this.props.router
}
}
export default withRouter(Test);
class Plan extends React.Component {
render() {
const { url} = this.props
return (
<Page>
<Header
user={user}
pathname={url.pathname}
onLogout={() => onUser(null)}
onLogoRightClick={() => Router.push('/logos')}
/>
<SubMenu
subscription={subscription}
teamsAndUser={teamsAndUser}
teams={teams}
user={user}
url={url}
/>
</Page>
)
}
}
export default withAppContainer(withAuthRequired(Plan, 'signup'))
import { withRouter } from "next/router";
class Plan extends React.Component {
render() {
const { router} = this.props
return (
<Page>
<Header
user={user}
pathname={router.pathname}
onLogout={() => onUser(null)}
onLogoRightClick={() => Router.push('/logos')}
/>
<SubMenu
subscription={subscription}
teamsAndUser={teamsAndUser}
teams={teams}
user={user}
url={router}
/>
</Page>
);
}
}
export default withRouter(withAppContainer(withAuthRequired(Plan, 'signup')));
export default withAppContainer(
withAuth(
class BuyDomains extends React.Component {
something = ({url}) => {
}
}
)
)
export default withAppContainer(
withAuth(
class BuyDomains extends React.Component {
something = ({url}) => {
}
}
)
)
export default class extends React.Component {}
\ No newline at end of file
export default class extends React.Component {}
\ No newline at end of file
const examples = [{ name: 'ex1', url: 'https://google.fr/' }]
export default () => (
<div>
{examples.map(example => (
<div key={example.name}>
{example.name} - {example.url}
</div>
))}
</div>
)
\ No newline at end of file
const examples = [{ name: 'ex1', url: 'https://google.fr/' }]
export default () => (
<div>
{examples.map(example => (
<div key={example.name}>
{example.name} - {example.url}
</div>
))}
</div>
)
\ No newline at end of file
export default (class extends React.Component {
render() {
const test = this.props.url
}
})
import { withRouter } from "next/router";
export default withRouter(class extends React.Component {
render() {
const test = this.props.router
}
});
const Test = class extends React.Component {
render() {
const test = this.props.url
}
}
export default abc(wrappingFunction(Test))
import { withRouter } from "next/router";
const Test = class extends React.Component {
render() {
const test = this.props.router
}
}
export default withRouter(abc(wrappingFunction(Test)));
\ No newline at end of file
export default withAppContainer(
withAuth(
class Blog extends React.Component {
render() {
const { props, state } = this
return (
<Header
inverse={true}
user={props.user}
pathname={props.url.pathname}
onLogout={() => {
props.onUser(null)
props.url.push('/login')
}}
onLogoRightClick={() => props.url.push('/logos')}
/>
)
}
}
)
)
import { withRouter } from "next/router";
export default withRouter(withAppContainer(withAuth(
class Blog extends React.Component {
render() {
const { props, state } = this
return (
<Header
inverse={true}
user={props.user}
pathname={props.router.pathname}
onLogout={() => {
props.onUser(null)
props.router.push('/login')
}}
onLogoRightClick={() => props.router.push('/logos')}
/>
);
}
}
)));
\ No newline at end of file
import Router from 'next/router'
export default class extends React.Component {
render() {
const test = this.props.url
}
}
import Router, { withRouter } from 'next/router';
export default withRouter(class extends React.Component {
render() {
const test = this.props.router
}
});
export default class extends React.Component {
render() {
const test = this.props.url
}
}
import { withRouter } from "next/router";
export default withRouter(class extends React.Component {
render() {
const test = this.props.router
}
});
export default withSomethingElse(class extends React.Component {
render() {
const test = this.props.url
}
})
import { withRouter } from "next/router";
export default withRouter(withSomethingElse(class extends React.Component {
render() {
const test = this.props.router
}
}));
import { withAmp, withAmp as alternative } from 'next/amp'
export default alternative(function Home() {
return <h1>My AMP Page</h1>
})
export default function Home() {
return <h1>My AMP Page</h1>
};
export const config = {
amp: true
};
import { withAmp } from 'next/amp'
function Home() {
return <h1>My AMP Page</h1>
}
export const config = {
foo: 'bar',
amp: false
}
export default withAmp(Home)
function Home() {
return <h1>My AMP Page</h1>
}
export const config = {
foo: 'bar',
amp: true
}
export default Home;
import { withAmp } from 'next/amp'
function Home() {
const config = {}
return <h1>My AMP Page</h1>
}
const config = {
foo: 'bar',
}
export default withAmp(Home)
export { config }
function Home() {
const config = {}
return <h1>My AMP Page</h1>
}
const config = {
foo: 'bar',
amp: true
}
export default Home;
export { config }
import { withAmp, useAmp } from 'next/amp'
function Home() {
const config = {}
return <h1>My AMP Page</h1>
}
export const config = {
foo: 'bar',
}
export default withAmp(Home)
import { useAmp } from 'next/amp';
function Home() {
const config = {}
return <h1>My AMP Page</h1>
}
export const config = {
foo: 'bar',
amp: true
}
export default Home;
import { withAmp } from 'next/amp'
function Home() {
const config = {}
return <h1>My AMP Page</h1>
}
export default withAmp(Home)
function Home() {
const config = {}
return <h1>My AMP Page</h1>
}
export default Home;
export const config = {
amp: true
};
import { withAmp } from 'next/amp'
function Home() {
const config = {}
return <h1>My AMP Page</h1>
}
export const config = {
foo: 'bar',
}
export default withAmp(Home, { hybrid: true })
function Home() {
const config = {}
return <h1>My AMP Page</h1>
}
export const config = {
foo: 'bar',
amp: "hybrid"
}
export default Home;
import { withAmp } from 'next/amp'
function Home() {
const config = {}
return <h1>My AMP Page</h1>
}
export default withAmp(Home, { hybrid: true })
function Home() {
const config = {}
return <h1>My AMP Page</h1>
}
export default Home;
export const config = {
amp: "hybrid"
};
/* global jest */
jest.autoMockOff()
const defineTest = require('jscodeshift/dist/testUtils').defineTest
const fixtures = [
'function-component',
'function-component-2',
'function-component-ignore',
'function-expression',
'function-expression-ignore',
'existing-name',
'existing-name-2',
'existing-name-3',
'existing-name-ignore',
'1-starts-with-number',
'special-ch@racter',
]
fixtures.forEach((test) =>
defineTest(
__dirname,
'name-default-component',
null,
`name-default-component/${test}`
)
)
/* global jest */
jest.autoMockOff()
const defineTest = require('jscodeshift/dist/testUtils').defineTest
const fixtures = [
'with-router-import',
'without-import',
'already-using-withrouter',
'using-inline-class',
'export-default-variable',
'export-default-variable-wrapping',
'no-transform',
'no-transform-method',
'wrapping-export',
'variable-export',
'arrow-function-component',
'destructuring-this',
'destructuring-this-class',
'destructuring-this-props',
'destructuring-this-props-nested',
'with-nested-arrow-function',
'componentdidupdate',
'componentwillreceiveprops',
'first-parameter-hoc',
'url-property-not-part-of-this-props',
]
for (const fixture of fixtures) {
defineTest(
__dirname,
'url-to-withrouter',
null,
`url-to-withrouter/${fixture}`
)
}
/* global jest */
jest.autoMockOff()
const defineTest = require('jscodeshift/dist/testUtils').defineTest
const fixtures = [
'remove-import',
'remove-import-renamed',
'remove-import-single',
'full-amp',
'full-amp-inline',
'full-amp-with-config',
'full-amp-with-config-dupe',
'full-amp-with-config-var',
'hybrid-amp',
'hybrid-amp-with-config',
]
for (const fixture of fixtures) {
defineTest(
__dirname,
'withamp-to-config',
null,
`withamp-to-config/${fixture}`
)
}
import { basename, extname } from 'path'
const camelCase = (value) => {
const val = value.replace(/[-_\s.]+(.)?/g, (_match, chr) =>
chr ? chr.toUpperCase() : ''
)
return val.substr(0, 1).toUpperCase() + val.substr(1)
}
const isValidIdentifier = (value) => /^[a-zA-ZÀ-ÿ][0-9a-zA-ZÀ-ÿ]+$/.test(value)
export default function transformer(file, api, options) {
const j = api.jscodeshift
const root = j(file.source)
let hasModifications
const returnsJSX = (node) =>
node.type === 'JSXElement' ||
(node.type === 'BlockStatement' &&
j(node)
.find(j.ReturnStatement)
.some(
(path) =>
path.value.argument && path.value.argument.type === 'JSXElement'
))
const hasRootAsParent = (path) => {
const program = path.parentPath.parentPath.parentPath.parentPath.parentPath
return (
!program || (program && program.value && program.value.type === 'Program')
)
}
const nameFunctionComponent = (path) => {
const node = path.value
if (!node.declaration) {
return
}
const isArrowFunction =
node.declaration.type === 'ArrowFunctionExpression' &&
returnsJSX(node.declaration.body)
const isAnonymousFunction =
node.declaration.type === 'FunctionDeclaration' && !node.declaration.id
if (!(isArrowFunction || isAnonymousFunction)) {
return
}
const fileName = basename(file.path, extname(file.path))
let name = camelCase(fileName)
// If the generated name looks off, don't add a name
if (!isValidIdentifier(name)) {
return
}
// Add `Component` to the end of the name if an identifier with the
// same name already exists
while (root.find(j.Identifier, { name }).some(hasRootAsParent)) {
// If the name is still duplicated then don't add a name
if (name.endsWith('Component')) {
return
}
name += 'Component'
}
hasModifications = true
if (isArrowFunction) {
path.insertBefore(
j.variableDeclaration('const', [
j.variableDeclarator(j.identifier(name), node.declaration),
])
)
node.declaration = j.identifier(name)
} else {
// Anonymous Function
node.declaration.id = j.identifier(name)
}
}
root.find(j.ExportDefaultDeclaration).forEach(nameFunctionComponent)
return hasModifications ? root.toSource(options) : null
}
This diff is collapsed.
// One-time usage file. You can delete me after running the codemod!
function injectAmp(j, o, desiredAmpValue) {
const init = o.node.init
switch (init.type) {
case 'ObjectExpression': {
const overwroteAmpKey = init.properties.some((prop) => {
switch (prop.type) {
case 'Property':
case 'ObjectProperty':
if (!(prop.key.type === 'Identifier' && prop.key.name === 'amp')) {
return false
}
prop.value = desiredAmpValue
return true
default:
return false
}
})
if (!overwroteAmpKey) {
init.properties.push(
j.objectProperty(j.identifier('amp'), desiredAmpValue)
)
}
return true
}
default: {
return false
}
}
}
export default function transformer(file, api) {
const j = api.jscodeshift
const root = j(file.source)
const done = () => root.toSource()
const imports = root.find(j.ImportDeclaration, {
source: { value: 'next/amp' },
})
if (imports.length < 1) {
return
}
let hadWithAmp = false
const ampImportNames = []
imports.forEach((ampImport) => {
const ampImportShift = j(ampImport)
const withAmpImport = ampImportShift.find(j.ImportSpecifier, {
imported: { name: 'withAmp' },
})
if (withAmpImport.length < 1) {
return
}
hadWithAmp = true
withAmpImport.forEach((element) => {
ampImportNames.push(element.value.local.name)
j(element).remove()
})
if (ampImport.value.specifiers.length === 0) {
ampImportShift.remove()
}
})
if (!hadWithAmp) {
return done()
}
const defaultExportsShift = root.find(j.ExportDefaultDeclaration)
if (defaultExportsShift.length < 1) {
return done()
}
let desiredAmpValue = j.booleanLiteral(true)
const defaultExport = defaultExportsShift.nodes()[0]
const removedWrapper = ampImportNames.some((ampImportName) => {
const ampWrapping = j(defaultExport).find(j.CallExpression, {
callee: { name: ampImportName },
})
if (ampWrapping.length < 1) {
return false
}
ampWrapping.forEach((e) => {
if (e.value.arguments.length < 1) {
j(e).remove()
} else {
const withAmpOptions = e.value.arguments[1]
if (withAmpOptions && withAmpOptions.type === 'ObjectExpression') {
const isHybrid = withAmpOptions.properties.some((prop) => {
if (!(prop.type === 'Property' || prop.type === 'ObjectProperty')) {
return false
}
if (!(prop.key && prop.key.name === 'hybrid')) {
return false
}
return (
(prop.value.type === 'Literal' ||
prop.value.type === 'BooleanLiteral') &&
prop.value.value === true
)
})
if (isHybrid) {
desiredAmpValue = j.stringLiteral('hybrid')
}
}
j(e).replaceWith(e.value.arguments[0])
}
})
return true
})
if (!removedWrapper) {
return done()
}
const namedExportsShift = root.find(j.ExportNamedDeclaration)
const hadExistingConfig = namedExportsShift.some((namedExport) => {
const configExportedObject = j(namedExport).find(j.VariableDeclarator, {
id: { name: 'config' },
})
if (configExportedObject.length > 0) {
return configExportedObject.some((exportedObject) =>
injectAmp(j, exportedObject, desiredAmpValue)
)
}
const configReexported = j(namedExport).find(j.ExportSpecifier, {
local: { name: 'config' },
})
if (configReexported.length > 0) {
const configObjects = root
.findVariableDeclarators('config')
.filter((el) => el.scope.isGlobal)
return configObjects.some((configObject) =>
injectAmp(j, configObject, desiredAmpValue)
)
}
return false
})
if (!hadExistingConfig) {
defaultExportsShift.insertAfter(
j.exportNamedDeclaration(
j.variableDeclaration('const', [
j.variableDeclarator(
j.identifier('config'),
j.objectExpression([
j.objectProperty(j.identifier('amp'), desiredAmpValue),
])
),
])
)
)
}
return done()
}
{
"compilerOptions": {
"module": "commonjs",
"sourceMap": true,
"esModuleInterop": true,
"target": "es2015",
"downlevelIteration": true,
"preserveWatchOutput": true
},
"include": ["**/*.ts"],
"exclude": ["node_modules"]
}
......@@ -115,13 +115,16 @@ class FontOptimizerMiddleware implements PostProcessMiddleware {
(tag: HTMLElement) =>
tag.getAttribute('rel') === 'stylesheet' &&
tag.hasAttribute('data-href') &&
OPTIMIZED_FONT_PROVIDERS.some((url) =>
tag.getAttribute('data-href').startsWith(url)
)
OPTIMIZED_FONT_PROVIDERS.some((url) => {
const dataHref = tag.getAttribute('data-href')
return dataHref ? dataHref.startsWith(url) : false
})
)
.forEach((element: HTMLElement) => {
const url = element.getAttribute('data-href')
this.fontDefinitions.push(url)
if (url) {
this.fontDefinitions.push(url)
}
})
}
mutate = async (
......@@ -164,7 +167,15 @@ class ImageOptimizerMiddleware implements PostProcessMiddleware {
break
}
}
_data.preloads.images = eligibleImages.map((el) => el.getAttribute('src'))
_data.preloads.images = []
for (const imgEl of eligibleImages) {
const src = imgEl.getAttribute('src')
if (src) {
_data.preloads.images.push(src)
}
}
}
mutate = async (markup: string, _data: postProcessData) => {
let result = markup
......@@ -203,9 +214,14 @@ function imageIsNotTooSmall(imgElement: HTMLElement): boolean {
return true
}
try {
const heightAttr = imgElement.getAttribute('height')
const widthAttr = imgElement.getAttribute('width')
if (!heightAttr || !widthAttr) {
return true
}
if (
parseInt(imgElement.getAttribute('height')) *
parseInt(imgElement.getAttribute('width')) <=
parseInt(heightAttr) * parseInt(widthAttr) <=
IMAGE_PRELOAD_SIZE_THRESHOLD
) {
return false
......
This diff is collapsed.
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