【问题标题】:Next.js typescript next.config.js doesn't workNext.js 打字稿 next.config.js 不起作用
【发布时间】:2021-09-25 05:25:18
【问题描述】:

我尝试将 Next.js 与 TypeScript 一起使用,我需要添加自定义配置。我创建了一个 next.config.js 文件,但看起来 Next.js 没有加载它。例如自定义环境变量不可用。这是我的 next.config.js

const withPlugins = require("next-compose-plugins");
const optimizedImages = require("next-optimized-images");

module.exports = withPlugins([
  [
    optimizedImages,
    {
      /* config for next-optimized-images */
      optimizeImages: false,
    },
  ],
  {
    reactStrictMode: true,
    // images: {
    //   domains: ['localhost:3000'],
    //   path: `uploads/_next/image`
    // imageSizes: [16, 32, 48, 64, 96, 128, 256, 384]
    // },
    env: {
      baseUrl: "http://localhost:3001",
      apiUrl: "http://localhost:5000",
    },
  },

  // your other plugins here
]);

例如,当我尝试访问类似 process.env.baseUrl 的 baseUrl 时,我得到一个错误

服务器错误 错误:baseUrl 未定义。

同样的配置在 Next.js 的 JavaScript 版本中工作正常。

那我做错了什么?

【问题讨论】:

  • 您应该使用.env 文件设置环境变量。我建议阅读Environment Variables in Next.js
  • 是的,我已经这样做了。谢谢。但我的问题是关于如何在 TypeScript 版本中使用自定义配置?
  • 如果您已使用.env 文件进行设置,则无需在next.config.js 中设置环境变量。只需访问出现在.env 文件中的变量,例如process.env.YOUR_ENV_VAR。这与您使用的语言无关。

标签: javascript node.js typescript next.js


【解决方案1】:

它与打字稿无关。 Typescript 对 next.js 没有任何控制权,它会检查类型。在当前的 next.js 设置中,当你安装时,如果你选择使用 typescript,next.js 已经为你配置好了 typescript。

您在 .env 文件中使用的变量将只能由服务器访问。如果需要为客户端设置环境变量,则在 next.config.js 中设置

module.exports = {
  webpack: (config) => {
    // this is where you add custom configuration for webpack
    return config;
  },
 
  env: {
  // this is where you set env variables for the client side
    BASE_URL: process.env.BASE_URL,
    
  },
  pwa: {
   // this where you add progressive web app setting
    dest: "public",
    swSrc: "service-worker.js",
   },
};

【讨论】:

    猜你喜欢
    • 2020-03-18
    • 1970-01-01
    • 2017-02-20
    • 2018-02-08
    • 2016-11-21
    • 1970-01-01
    • 2016-06-16
    • 2018-05-25
    • 2018-12-25
    相关资源
    最近更新 更多