如何在 Next.js 中使用 module.exports

How to use module.exports in Next.js

在我的 next.js 应用程序中,我试图在我的 next.config.js 中公开这个 env 对象,然后 prescription 到我的应用程序;

//next.config.js

const withCSS = require('@zeit/next-css');

module.exports = withCSS({
  webpack(config) {
    config.module.rules.push({
      test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
      use: {
        loader: 'url-loader',
        options: {
          limit: 100000,
          name: '[name].[ext]'
        }
      }
    });
    return config;
  }
});

  //trying to expose the env {} below

    module.exports = {
      env: {
        DEVELOPMENT_DB_DSN: 'mongodb+srv://antonioHillfinder:foo@hillfinder-qjxuo.azure.mongodb.net/development?retryWrites=true&w=majority',
        PRODUCTION_DB_DSN: 'mongodb+srv://antonioHillfinder:bar@hillfinder-qjxuo.azure.mongodb.net/production?retryWrites=true&w=majority',
        TEST_DB_DSN: 'mongodb+srv://antonioHillfinder:foobar@hillfinder-qjxuo.azure.mongodb.net/test?retryWrites=true&w=majority'
      }
    };

我也试过这个:

var withCSS = require('@zeit/next-css');


module.exports = {
  withCSS: withCSS({
    webpack(config) {
      config.module.rules.push({
        test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 100000,
            name: '[name].[ext]'
          }
        }
      });
      return config;
    }
  }),
  env: {
    DEVELOPMENT_DB_DSN: `mongodb+srv://antonioHillfinder:foo@hillfinder-qjxuo.azure.mongodb.net/development?retryWrites=true&w=majority`,
    PRODUCTION_DB_DSN: `mongodb+srv://antonioHillfinder:bar@hillfinder-qjxuo.azure.mongodb.net/production?retryWrites=true&w=majority`,
    TEST_DB_DSN: `mongodb+srv://antonioHillfinder:foobar@hillfinder-qjxuo.azure.mongodb.net/test?retryWrites=true&w=majority`
  }
};

我正在尝试在这里使用它们:

var express = require('express')
var next = require('next')
var session = require('express-session')
var MongoStore = require('connect-mongo')(session)
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var cors = require('cors')
var morgan = require('morgan')
var HttpStatus = require('http-status-codes')

var PORT = process.env.PORT || 8016
var dev = process.env.NODE_ENV !== `production`;

function processNODEENVCheckerAndServerRuntimeConfigSetter(ENV) {
  var environment,
    environments = {
      'production': () => {
        environment = process.env.PRODUCTION_DB_DSN; //trying to use them here
        return environment;
      },
      'test': () => {
        environment = process.env.TEST_DB_DSN; //trying to use them here
        return environment;
      },
      'default': () => {
        environment = process.env.DEVELOPMENT_DB_DSN; //trying to use them here
        console.log("environment ", environment);
        return environment;
      },
    };
  (environments[ENV] || environments['default'])();

  return environment
}

var db = processNODEENVCheckerAndServerRuntimeConfigSetter(process.env.NODE_ENV)

var NextApp = next({ dev })
var handle = NextApp.getRequestHandler()

var mongoose = require('mongoose')

NextApp.prepare()
  .then(() => {
    const app = express()
    mongoose.connect(db, { useNewUrlParser: true })
    mongoose.Promise = global.Promise

    mongoose.connection
      .on('connected', () => {
        console.log(`Mongoose connection open on ${db}`)
      })
      .on('error', err => {
        console.log(`Connection error: ${err.message}`)
      })

    app.use(bodyParser.json())
    app.use(bodyParser.urlencoded({ extended: true }))
    app.use(morgan('dev'))

    app.use(cookieParser())

    session({
      secret: 'very secret 12345',
      resave: true,
      saveUninitialized: false,
      store: new MongoStore({ mongooseConnection: mongoose.connection })
    })

    app.use(cors())

    app.use('/auth', require('./auth'))

    app.get('*', (req, res) => {
      return handle(req, res)
    })

    app.use(errorHandler, function (error, req, res, next) {
      res.json({ message: error.message })
    })

    app.listen(PORT, err => {
      if (err) throw err
      console.log(`> Ready on http://localhost:${PORT}`)
    })
  })
  .catch(err => {
    console.error(err)
  })

最后应用程序崩溃了,我收到了这个错误...

environment  undefined

Compiled successfully!

Note that pages will be compiled when you first load them.
{ MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
    at new MongooseError (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongoose/lib/error/mongooseError.js:10:11)
    at NativeConnection.Connection.openUri (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongoose/lib/connection.js:519:11)
    at Mongoose.connect (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongoose/lib/index.js:314:15)
    at NextApp.prepare.then (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/server/index.js:68:14)
    at process._tickCallback (internal/process/next_tick.js:68:7)
  message:
   'The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.',
  name: 'MongooseError' }
[nodemon] clean exit - waiting for changes before restart

不知道为什么我在 var db = processNODEENVCheckerAndServerRuntimeConfigSetter(process.env.NODE_ENV) statement/function

中从 console.log("environment ", environment); 得到 undefined

使用 next.config.js 中的 env 选项只会使环境变量在构建时可用。

要让环境变量可用于您的服务器,您可以将环境变量放在项目根目录下的 .env 文件中:

DEVELOPMENT_DB_DSN="mongodb+srv://antonioHillfinder:foo@hillfinder-qjxuo.azure.mongodb.net/development?retryWrites=true&w=majority"
PRODUCTION_DB_DSN="mongodb+srv://antonioHillfinder:bar@hillfinder-qjxuo.azure.mongodb.net/production?retryWrites=true&w=majority"
TEST_DB_DSN="mongodb+srv://antonioHillfinder:foobar@hillfinder-qjxuo.azure.mongodb.net/test?retryWrites=true&w=majority"

然后就可以使用dotenv包来加载了:

https://www.npmjs.com/package/dotenv

npm i dotenv

...并将其添加到服务器文件的顶部:

require('dotenv').config()

此后,您的环境变量将在您的服务器上可用。




注意,next.config.js中的env选项是为了让环境变量在构建过程中可用,可以像这样使用:

// next.config.js

const withCSS = require('@zeit/next-css');

module.exports = withCSS({
  webpack(config) {
    // ...
    return config;
  },
  env: {
    // ...
  }
});