NextJS教程

Next.js 环境变量

Next.js,支持在节点中发布环境变量,我们可以使用它来连接服务器、数据库等。为此,我们需要在根目录下创建 .env.local 文件。我们也可以创建 .env.production。

创建 .env.local

在根目录下创建.env.local,内容如下。
DB_HOST=localhost
DB_USER=Lidihuo
DB_PASS=nextjs

创建 env.js

在 pages/posts 目录中创建一个名为 env.js 的页面,其中包含以下内容,我们将使用 process.env 使用环境变量。
import Head from 'next/head'
import Container from '../../components/container'
export default function FirstPost(props) {
   return (
      <>
         <Container>
            <Head>
               <title>Environment Variables</title>
            </Head>
            <h1>Database Credentials</h1>
               <p>Host: {props.host}</p>
               <p>Username: {props.username}</p>
               <p>Password: {props.password}</p>
         </Container>
      </>	  
   )
}
export async function getStaticProps() {
   // Connect to Database using DB properties
   return {
      props: { 
         host: process.env.DB_HOST,
         username: process.env.DB_USER,
         password: process.env.DB_PASS
      }
   }
}
现在启动服务器。
Next.JS 将检测 .env.local 并在控制台上显示以下消息。
npm run dev
> nextjs@1.0.0 dev D:\Node\nextjs
> next
ready-started server on http://localhost:3000
info -Loaded env from D:\Node\nextjs\.env.local
event-compiled successfully
wait -compiling...
event-compiled successfully
event-build page: /posts/env
wait -compiling...
event-compiled successfully

验证输出

在浏览器中打开 localhost:3000/posts/env,您将看到以下输出。
环境变量
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4