Next.js高级特性:Next.js Codemods

当不推荐使用某个功能时,Next.js提供了Codemod转换以帮助升级您的Next.js代码库。

Codemod是以编程方式在您的代码库上运行的转换。这允许应用大量更改,而不必手动浏览每个文件。

用法

npx @next/codemod <transform> <path>

  • transform -转换名称,请参阅下面的可用转换。
  • path -要转换的文件或目录
  • --dry 进行试运行,不会编辑任何代码
  • --print 打印更改的输出以进行比较

Next.js 10

add-missing-react-import

转换不导入的文件React以包括导入,以使新的React JSX转换正常工作。

例如:

// my-component.js
export default class Home extends React.Component {
  render() {
    return <div>Hello World</div>
  }
}

转换为:

// my-component.js
import React from 'react'
export default class Home extends React.Component {
  render() {
    return <div>Hello World</div>
  }
}

Next.js 9

name-default-component

将匿名组件转换为命名组件,以确保它们可与Fast Refresh一起使用。

例如:

// my-component.js
export default function () {
  return <div>Hello World</div>
}

转换为:

// my-component.js
export default function MyComponent() {
  return 
Hello World
// my-component.js export default function MyComponent() { return <div>Hello World</div> }

该组件将具有基于文件名的驼峰式名称,并且还可以使用箭头功能。

用法

去你的项目

运行codemod:

npx @next/codemod name-default-component

withamp-to-config

withAmpHOC转换为Next.js 9页面配置。

例如:

// Before
import { withAmp } from 'next/amp'

function Home() {
  return <h1>My AMP Page</h1>
}

export default withAmp(Home)
// After
export default function Home() {
  return <h1>My AMP Page</h1>
}

export const config = {
  amp: true,
}

用法

去你的项目

cd path-to-your-project/

运行codemod:

npx @next/codemod withamp-to-config

Next.js 6

url-to-withrouter

url顶级页面上已弃用的自动注入属性转换为usingwithRouterrouter它注入的属性。在此处阅读更多信息:err.sh/next.js/不推荐使用url

例如:

// From
import React from 'react'
export default class extends React.Component {
  render() {
    const { pathname } = this.props.url
    return <div>Current pathname: {pathname}</div>
  }
}
// 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>
    }
  }
)

这只是一种情况。可以在__testfixtures__目录中找到所有经过转换(和测试)的案例。

用法

去你的项目

运行codemod:

npx @next/codemod url-to-withrouter

作者:terry,如若转载,请注明出处:https://www.web176.com/nextjs/2389.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2021年4月16日 下午6:05
下一篇 2021年4月16日 下午6:15

相关推荐

发表回复

登录后才能评论