使用自定义快递服务器无法在nextjs中解析'fs'

我将fs添加到我的nextjs项目中,并收到以下错误:

未找到模块:无法在'/ Users / neven / Development / next-js / node_modules / dotenv / lib'

中解析“ fs”

我发现要解决此问题,应将 config.node = {fs:'empty'} 添加到我的next.config.js文件中。 问题在于,当我添加该配置参数时,dotenv插件将停止工作,即在客户端未加载env变量。

这是我的next.config.js文件,该文件可以正常运行。

const withCSS = require('@zeit/next-css')
const dotenv = require('dotenv')
const path = require('path')
const Dotenv = require('dotenv-webpack')

dotenv.config()

module.exports = withCSS({
  webpack: config => {
    config.plugins = config.plugins || []

    config.plugins = [
      ...config.plugins,// Read the .env file
      new Dotenv({
        path: path.join(__dirname,'.env'),systemvars: true,}),]

    return config
  },})

然后当我添加 fs:'empty'时,它看起来像这样:

const withCSS = require('@zeit/next-css')
const dotenv = require('dotenv')
const path = require('path')
const Dotenv = require('dotenv-webpack')

dotenv.config()

module.exports = withCSS({
  webpack: config => {
    config.plugins = config.plugins || []

    config.node = {
      fs: 'empty'
    }

    config.plugins = [
      ...config.plugins,})

您对我如何解决这个问题有任何建议吗?

如果需要其他详细信息,请告诉我。

ganmazhememahuan 回答:使用自定义快递服务器无法在nextjs中解析'fs'

我发现了问题所在; dotenv插件可以正常工作,但是我试图在客户端获取变量,而这种方式是不可能的。

在客户端使用env变量的解决方案是将 env:{示例:'helloWorld'} 添加到next.config.js文件。

const withCSS = require('@zeit/next-css')
const dotenv = require('dotenv')
const path = require('path')
const Dotenv = require('dotenv-webpack')

dotenv.config()

module.exports = withCSS({
  env: { EXAMPLE: 'helloWorld' },webpack: config => {
    config.plugins = config.plugins || []

    config.node = {
      fs: 'empty'
    }

    config.plugins = [
      ...config.plugins,// Read the .env file
      new Dotenv({
        path: path.join(__dirname,'.env'),systemvars: true,}),]

    return config
  },})
,

这里的问题是您的客户端无法访问环境变量。

Started NextJS 9.4,您可以使用 .env* 文件添加环境变量。

为了让您的客户端访问环境变量,您只需在它们前面加上 NEXT_PUBLIC_

NEXT_PUBLIC_YOUR_KEY="keykeykey"

这些可以通过以下方式访问:

process.env.NEXT_PUBLIC_YOUR_KEY
本文链接:https://www.f2er.com/2524988.html

大家都在问