当前位置: 首页 > 文档资料 > Next.js 中文文档 >

自定义配置

优质
小牛编辑
138浏览
2023-12-01

如果你想自定义 Next.js 的高级配置,可以在根目录下新建next.config.js文件(与pages/package.json一起)

注意:next.config.js是一个 Node.js 模块,不是一个 JSON 文件,可以用于 Next 启动服务已经构建阶段,但是不作用于浏览器端。

// next.config.js
module.exports = {
  /* config options here */
}

或使用一个函数:

module.exports = (phase, {defaultConfig}) => {
  //
  // https://github.com/zeit/
  return {
    /* config options here */
  }
}

phase是配置文件被加载时的当前内容。你可看到所有的 phases 常量: 这些常量可以通过next/constants引入:

const {PHASE_DEVELOPMENT_SERVER} = require('next/constants')
module.exports = (phase, {defaultConfig}) => {
  if(phase === PHASE_DEVELOPMENT_SERVER) {
    return {
      /* development only config options here */
    }
  }

  return {
    /* config options for all phases except development here */
  }
}

设置自定义构建目录

你可以自定义一个构建目录,如新建build文件夹来代替.next 文件夹成为构建目录。如果没有配置构建目录,构建时将会自动新建.next文件夹

// next.config.js
module.exports = {
  distDir: 'build'
}

禁止 etag 生成

你可以禁止 etag 生成根据你的缓存策略。如果没有配置,Next 将会生成 etags 到每个页面中。

// next.config.js
module.exports = {
  generateEtags: false
}

配置 onDemandEntries

Next 暴露一些选项来给你控制服务器部署以及缓存页面:

module.exports = {
  onDemandEntries: {
    // period (in ms) where the server will keep pages in the buffer
    maxInactiveAge: 25 * 1000,
    // number of pages that should be kept simultaneously without being disposed
    pagesBufferLength: 2,
  }
}

这个只是在开发环境才有的功能。如果你在生成环境中想缓存 SSR 页面,请查看SSR-caching

配置页面后缀名解析扩展

如 typescript 模块@zeit/next-typescript,需要支持解析后缀名为.ts的文件。pageExtensions 允许你扩展后缀名来解析各种 pages 下的文件。

// next.config.js
module.exports = {
  pageExtensions: ['jsx', 'js']
}

配置构建 ID

Next.js 使用构建时生成的常量来标识你的应用服务是哪个版本。在每台服务器上运行构建命令时,可能会导致多服务器部署出现问题。为了保持同一个构建 ID,可以配置generateBuildId函数:

// next.config.js
module.exports = {
  generateBuildId: async () => {
    // For example get the latest git commit hash here
    return 'my-build-id'
  }
}