如何在带有 TypeScript 的 next.config.js 中使用 i18n 和 next/image?

Posted

技术标签:

【中文标题】如何在带有 TypeScript 的 next.config.js 中使用 i18n 和 next/image?【英文标题】:How to use i18n and next/image in next.config.js with TypeScript? 【发布时间】:2021-04-11 21:15:39 【问题描述】:

我正在尝试在 NextJS 中使用 TypeScript 创建一个迷你应用程序,因为现在 Next.js 支持 TypeScript。而且我还想合并这两个新添加的功能:

Image Component and Image Optimization (next/image) Internationalized Routing (i18n)

i18n为例:

// next.config.js
module.exports = 
    i18n: 
      // These are all the locales you want to support in
      // your application 
      // Sub-path Routing 
      locales: ['en', 'cn'],
      // This is the default locale you want to be used when visiting
      // a non-locale prefixed path e.g. `/hello`
      defaultLocale: 'en',
    ,
  

不幸的是,我很难在我的next.config.js 中使用它们,至于普通应用程序(仅限 javascript),它可以正常工作。但是对于 TypeScript 版本,我收到了这个错误:

(node:15704) UnhandledPromiseRejectionWarning: TypeError: Cannot set property '__nextLocale' of undefined

如果你们中的任何人能帮助我或者举个例子说明如何正确使用 next.config.js 并将这些新功能整合到 TypeScript NextJS 应用程序中,这将非常有帮助。

【问题讨论】:

【参考方案1】:

我认为没有'en'和'cn'的语言环境

https://en.wikipedia.org/wiki/Language_localisation

我认为你需要的是:

const withImages = require('next-images')
const withPWA = require('next-pwa')

module.exports = withPWA(
withImages(
  images: 
    domains: [
    'images.ctfassets.net',
    'imgix.cosmicjs.com',
    'cdn.cosmicjs.com',
   ],
   i18n: 
      // These are all the locales you want to support in
      // your application
      locales: ['en-US', 'zh-CN'],
      // This is the default locale you want to be used when visiting
      // a non-locale prefixed path e.g. `/hello`
      defaultLocale: 'pt-BR',
      ...
   
 ,

【讨论】:

区域在Next.js i18n locales 中是可选的。

以上是关于如何在带有 TypeScript 的 next.config.js 中使用 i18n 和 next/image?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 React 上正确使用带有样式组件画布的 TypeScript 类型

如何在带有接口的 Typescript 中声明公共和私有变量?

如何在 TypeScript 中键入带有类的数组?

如何在带有 Typescript 的视图中使用 Vue 单文件组件?

如何在带有 Typescript 项目的 React Native 中使用 AWS Amplify?

如何在 TypeScript 中使用带有 React 无状态功能组件的子组件?