Created
March 15, 2019 14:38
-
-
Save anthonny/54bf484b3633d934dfe17d036c9f8b58 to your computer and use it in GitHub Desktop.
Use dotenv with NativeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... | |
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), | |
// ... | |
// ... |
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
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
How do you reference this within the app?