Next.js Environment Variables All In One
<h1 id="nextjs-environment-variables-all-in-one">Next.js Environment Variables All In One</h1><blockquote>
<p>.env</p>
</blockquote>
<p><code>.env.local</code></p>
<pre><code class="language-code">DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword
</code></pre>
<pre><code class="language-js">// getStaticProps:
// pages/index.js
export async function getStaticProps() {
const db = await myDB.connect({
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS,
})
// ...
}
</code></pre>
<p><code>NEXT_PUBLIC_</code></p>
<pre><code class="language-code">NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk
</code></pre>
<pre><code class="language-js">// pages/index.js
import setupAnalyticsService from '../lib/my-analytics-service'
// 'NEXT_PUBLIC_ANALYTICS_ID' can be used here as it's prefixed by 'NEXT_PUBLIC_'.
// It will be transformed at build time to `setupAnalyticsService('abcdefghijk')`.
setupAnalyticsService(process.env.NEXT_PUBLIC_ANALYTICS_ID)
function HomePage() {
return <h1>Hello World</h1>
}
export default HomePage
</code></pre>
<p>https://nextjs.org/docs/basic-features/environment-variables</p>
<p>https://nextjs.org/docs/api-reference/next.config.js/environment-variables</p>
<h2 id="demo">demo</h2>
<pre><code class="language-env">//process.env
</code></pre>
<p><img src="https://img2022.cnblogs.com/blog/740516/202211/740516-20221104121038836-2091911583.png" alt="image" loading="lazy"></p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/vS86x_e0zBk?start=29" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""></iframe>
<h2 id="refs">refs</h2>
<hr>
<div>
</div>
<hr>
<blockquote style="display: flex; flex-flow: column; align-items: center; justify-content: center; text-align: center; border: none">
<h3><strong><span style="font-size: 16pt; color: rgba(0, 255, 0, 1)">©xgqfrms 2012-<span data-uid="copyright-aside">2021</span></span></strong>
<p><span style="font-size: 18pt; color: rgba(0, 255, 0, 1)"><strong>www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!</strong></span></p>
<p><span style="font-size: 18pt; color: rgba(0, 255, 0, 1)"><strong>原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!</strong></span></p>
</h3></blockquote>
<hr>
</div>
<div id="MySignature" role="contentinfo">
<div style="display: flex; flex-flow: column nowrap; align-items: center; justify-content: center;">
<p>本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16857358.html</p>
<p style="color: red; font-size: 23px; margin-top: 5px; margin-botom: 5px;">未经授权禁止转载,违者必究!</P>
</div>
<hr/><br><br>
来源:https://www.cnblogs.com/xgqfrms/p/16857358.html
頁:
[1]