如何在Nextjs项目中组织.env文件



.env文件在根目录中运行良好,但我想将所有env文件组织到一个文件夹中,如下所示。

ProjectRoot
└ env
└ .env.development
└ .env.local
(...)

但Nextjs并没有从福特那里读到各种各样的东西。

我尝试将env路径添加到tsconfig.json

{
"compilerOptions" : { (...) },
"include" : [
(...),
"env/.env*"
],
(...)
}

不起作用。。

这是我的package.jsonnext.config.js文件。

// package.json
{
(...),
"dependencies": {
"@emotion/react": "^11.10.4",
"@emotion/styled": "^11.10.4",
"@mui/icons-material": "^5.10.9",
"@mui/material": "^5.10.9",
"axios": "^1.1.3",
"babel-preset-next": "^1.4.0",
"cross-env": "^7.0.3",
"next": "12.3.1",
"next-translate": "^1.6.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-icons": "^4.6.0",
"react-markdown": "^6.0.0",
"react-spring": "^9.0.0",
"react-syntax-highlighter": "^15.5.0",
"react-use-measure": "^2.1.1",
"react-wordcloud": "^1.2.7",
"rehype-raw": "^6.1.1",
"styled-components": "^5.3.6",
"styled-reset": "^4.4.2",
"swr": "^1.3.0"
},
"devDependencies": {
"@svgr/webpack": "^6.5.0",
"@types/node": "18.8.4",
"@types/react": "18.0.21",
"@types/react-dom": "18.0.6",
"@types/react-syntax-highlighter": "^15.5.5",
"@types/styled-components": "^5.1.26",
"babel-plugin-styled-components": "^2.0.7",
"eslint": "8.25.0",
"eslint-config-next": "12.3.1",
"typescript": "4.8.4"
}
}
// next.config.js
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
trailingSlash: true,
webpack: (config) => {
config.module.rules.push({
test: /.svg$/i,
issuer: /.[jt]sx?$/,
use: ["@svgr/webpack"],
});
return config;
},
};
module.exports = nextConfig;

有什么帮助吗?

您可以使用dotenv-webpack-npm包。

在next.cnfig.js 中

const Dotenv = require('dotenv-webpack');
module.exports = {
webpack(config) {
config.plugins.push(new webpack.Dotenv({
path: './yourNewEnvDirectory',
}))
return config
}
}