Create a file process-env.js
like:
"use strict";
const fs = require("fs");
const path = require("path");
const NODE_ENV = process.env.NODE_ENV || "dev";
const dotEnvPath = path.resolve(process.cwd(), ".env");
const dotenvFiles = [
`${dotEnvPath}.${NODE_ENV}.local`,
`${dotEnvPath}.${NODE_ENV}`,
NODE_ENV !== "test" && `${dotEnvPath}.local`,
dotEnvPath
].filter(Boolean);
dotenvFiles.forEach(dotenvFile => {
if (fs.existsSync(dotenvFile)) {
require("dotenv-expand")(
require("dotenv").config({
path: dotenvFile
})
);
}
});
const appDirectory = fs.realpathSync(process.cwd());
process.env.NODE_PATH = (process.env.NODE_PATH || "")
.split(path.delimiter)
.filter(folder => folder && !path.isAbsolute(folder))
.map(folder => path.resolve(appDirectory, folder))
.join(path.delimiter);
const SPFX_ = /^SPFX_/i;
function getClientEnvironment() {
const raw = Object.keys(process.env)
.filter(key => SPFX_.test(key))
.reduce((env, key) => {
env[key] = process.env[key];
return env;
}, {});
const stringified = {
"process.env": Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {})
};
return { raw, stringified };
}
module.exports = getClientEnvironment;
Next, append gulpfile.js
and add this right before the build.initialize() call:
const webpack = require("webpack");
const getClientEnvironment = require("./process-env");
build.configureWebpack.mergeConfig({
additionalConfiguration: cfg => {
let pluginDefine = null;
for (var i = 0; i < cfg.plugins.length; i++) {
var plugin = cfg.plugins[i];
if (plugin instanceof webpack.DefinePlugin) {
pluginDefine = plugin;
}
}
const currentEnv = getClientEnvironment().stringified;
if (pluginDefine) {
pluginDefine.definitions = { ...pluginDefine.definitions, ...currentEnv };
} else {
cfg.plugins.push(new webpack.DefinePlugin(currentEnv));
}
return cfg;
}
});
Then you can use these variables like:
let apiBaseUrl = process.env.SPFX_WEBAPI_BASEURL;
Reference: Using .env files in SharePoint Framework development
You can find full working code at: demo-spfx-dotenv
You can also use DefinePlugin
for this. follow this: How To Handle Env Variable Using DefinePlugin In SPFx Solutions
dotenv
: digitalworkplace365.wordpress.com/2020/03/05/… and this forDefinePlugin
: sharepointpals.com/post/…. Let me know if this works for you.