简体   繁体   English

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

[英]How to use module.exports in Next.js

In my next.js app, I am trying to expose this env object in my next.config.js following this prescription to my app; 在我的next.js应用程序中,我正在尝试按照next.config.js 对我的应用程序公开next.config.jsenv对象;

//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'
      }
    };

I tried this too: 我也尝试过这个:

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`
  }
};

And I'm trying to use them here: 我正在尝试在这里使用它们:

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)
  })

In the end the app just breaks and I get this error... 最后,应用程序坏了,我得到了这个错误...

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

Not sure why I get undefined from console.log("environment ", environment); 不知道为什么我从console.log("environment ", environment);得到undefined in the var db = processNODEENVCheckerAndServerRuntimeConfigSetter(process.env.NODE_ENV) statement/function var db = processNODEENVCheckerAndServerRuntimeConfigSetter(process.env.NODE_ENV)语句/函数中

Using the env option in next.config.js will only make the environment variables available at build time. next.config.js中使用env选项将仅在构建时使环境变量可用。

To have environment variables available to your server, you can put your environment variables in a .env file in the root of your project: 要使环境变量可用于服务器,可以将环境变量放在项目根目录下的.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"

Then you can use the dotenv package to load it: 然后,您可以使用dotenv软件包加载它:

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

npm i dotenv

...and add this at the top of your server file: ...并将其添加到服务器文件的顶部:

require('dotenv').config()

Thereafter, your environment variables will be available on your server. 之后,环境变量将在服务器上可用。




Note, the env option in next.config.js is to make environment variables available during a build and can be used like this: 注意, next.config.js中env选项用于使环境变量在构建期间可用,并且可以这样使用:

// next.config.js

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM