Skip to content

Instantly share code, notes, and snippets.

@anthonny
Created March 15, 2019 14:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonny/54bf484b3633d934dfe17d036c9f8b58 to your computer and use it in GitHub Desktop.
Save anthonny/54bf484b3633d934dfe17d036c9f8b58 to your computer and use it in GitHub Desktop.
Use dotenv with NativeScript
// ...
const dotenv = require("dotenv");
// ...
console.log(`Bundling application for entryPath ${entryPath}...`);
dotenv.config()
const isUppercase = key => key.toUpperCase() === key;
const envKeys = Object.keys(env);
let dotEnvValues = envKeys
.filter(isUppercase)
.reduce((memo, key) => {
return {...memo, [key]: JSON.stringify(env[key])};
}, {})
const dotEnvkeys = Object.keys(process.env);
dotEnvValues = dotEnvkeys
.filter(isUppercase)
.reduce((memo, key) => {
if (memo[key]) {
return memo;
}
return {...memo, [key]: dotEnvValues[key] || JSON.stringify(process.env[key])};
}, {...dotEnvValues})
const definitiveEnv = {
"global.TNS_WEBPACK": "true",
"TNS_ENV": JSON.stringify(mode),
...dotEnvValues
}
const config = {
// ...
plugins: [
// ... Vue Loader plugin omitted
// make sure to include the plugin!
new VueLoaderPlugin(),
// Define useful constants like TNS_WEBPACK
new webpack.DefinePlugin(definitiveEnv),
// ...
// ...
@jdavidbakr
Copy link

How do you reference this within the app?

@bencarter78
Copy link

How do you reference this within the app?

In your .env file, say you had a key of APP_URL, then within your app you would literally use that key to access the variable

@eikaramba
Copy link

eikaramba commented Jun 13, 2021

for ns8 you can do

(webpack.config.js)

const webpack = require("@nativescript/webpack");
const dotenv = require("dotenv");
module.exports = (env) => {
	webpack.init(env);

	dotenv.config()
    const isUppercase = key => key.toUpperCase() === key;
    const envKeys = Object.keys(env);
    let dotEnvValues = envKeys
        .filter(isUppercase)
        .reduce((memo, key) => {
            return {...memo, [key]: JSON.stringify(env[key])};
        }, {})

    const dotEnvkeys = Object.keys(process.env);
    dotEnvValues = dotEnvkeys
        .filter(isUppercase)
        .reduce((memo, key) => {
            if (memo[key]) {
                return memo;
            }

            return {...memo, [key]: dotEnvValues[key] || JSON.stringify(process.env[key])};
        }, {...dotEnvValues})

		// console.log(dotEnvValues);

		webpack.chainWebpack(config => {
			config.plugin('DefinePlugin').tap(args => {
			  Object.assign(args[0], dotEnvValues)
		
			  return args
			})
		  })

	return webpack.resolveConfig();
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment