Recommended dynamic runtime configuration technique on nuxtjs (other than dotenv) - vue.js

I have been trying to use publicRuntimeConfig / privateRuntimeConfig
On nuxt 2.4.1, I have defined my runtime config as follows on nuxt.config.js
publicRuntimeConfig: {
DATA_API_HOST_URL: process.env.VUE_APP_DATA_API_HOST_URL,
},
privateRuntimeConfig: {
AUTH_APP_CLIENT_SECRET: process.env.VUE_APP_AUTH_APP_CLIENT_SECRET,
},
and calling it as follows on my login.vue
asyncData( ctx ) {
console.log(ctx.$config.DATA_API_HOST_URL)
//some activity
}
The keys are showing up on $config inside asyncData. I debugged on chrome dev tools. But value is not read from process.env.VUE_APP_DATA_API_HOST_URL. The value is showing up as undefined. However, process.env.VUE_APP_DATA_API_HOST_URL is showing the value OK. The whole point is to move away from process.env.
this.$config.DATA_API_HOST_URL also does not access the values.
'${DATA_API_HOST_URL}' is shown in examples but I believe it is only for explicit param declarations at asyncData like asyncData( { $config : {DATA_API_HOST_URL}).
When I pass values as it is using DATA_API_HOST_URL: process.env.VUE_APP_DATA_API_HOST_URL || 'https://test.api.com', it seems to copy the value fine using ctx.$config.DATA_API_HOST_URL!
Looking to me like copying process.env to *RuntimeConfig has a problem!
What is the recommended way of importing and using runtime configurations?

As per documentation in the Nuxt blog post you marked, the feature your are trying to use is released in 2.13 (you´re using 2.4 if i not misunderstood). That could be the reason behind the behaviour you're seeing.
I'd recommend update your project dependencies or trying another approach.

I think you should use Docker to set dynamic runtime config like link below:
https://dev.to/frontendfoxes/dockerise-your-nuxt-ssr-app-like-a-boss-a-true-vue-vixens-story-4mm6

Related

Use env variable in VueJS SPA components at runtime?

I'm building a simple SPA with VueJs and Webpack, and would like to use/access env variables from my VueJS components.
I know I will not be able to change those variables "on the fly" but instead I need to recompile-rebuild-redeploy the entire application to see the changes, but for now it's ok since the actual need is to show different info and/or sections base on the deploy environment (local, staging, production).
To be more specific, for now I'm trying to get the env var COMMIT_HASH just to display it as some applications already do just for development info.
This variable would primarily used by the pipeline for the staging deployment, as in local development would be not that useful and probably not used at all for production deployment.
The problem is that I cannot figure out how to access env variables values from my VueJS components scripts sections at runtime, as process.env is a Node method accessible only during webpack compilation and not at runtime.
I thought about using string replacement and found this question, but then I would need to update Webpack script for any new env variable I need to use, so it looks quite inelegant to me.
I also tought of loading all the env variables in a js object and somehow pass it down to the files being compiled by Webpack, but this also looks inelegant/inefficient to me.
So now I'm stuck as can't figure out how to access env vars from my VueJS components at runtime.
I ended up using string-replace-loader with regex matching and a callback for dynamic replacement.
Basically I'll use env.SOME_VARIABLE in my code and search/replace it with the variable value.
For some reason I couldn't make the regex work with the \w to match for word characters and used [a-zA-Z_] instead.
{
test: /resources.*\.js$/,
loader: 'string-replace-loader',
options: {
search: 'env\.([a-zA-Z_]+)',
replace(match, p1, offset, string) {
return process.env[p1];
},
flags: 'g'
}
}
Notes
Since it is text replacement I cannot simply assign env variable values to vue component data properties as it would be interpreted as a variable:
// E.g. given env `COMMIT_HASH=some_hash`
data() {
return {
/**
* WRONG:
* this would be parsed as
* hash: some_hash
* leading to an
* Uncaught ReferenceError: some_hash is not defined
*/
hash: env.COMMIT_HASH,
/**
* RIGHT:
* wrap string to be replaced in single/double quotes so after
* replacement it became a string literal assignment.
* hash: "some_hash"
*/
hash: "env.COMMIT_HASH",
};
},

Accessing vuex modules data from within a plugin

I am moving some data from the vuex store into its own module. Most of it works great, but I'm running into an issue that I can't seem to fix.
I have a plugin that I add, and that plugin also needs access to the store.
So at the top of that plugin, we import the store:
import store from '../store/store';
great - further down that plugin, I'm accessing the data of the store in a method that I expose on the service:
hasPermission(permission) {
return (store.state.authorization.permissions.indexOf(permission) >= 0);
}
Please note authorization is now a seperate module, and is no longer part of the root state object.
now the funny thing is that the above will return an error telling me indexOf is not a function.
When I add the following, however:
hasPermission(permission) {
console.log('Validating permission ' + permission);
console.log(store.state);
return (store.state.authorization.permissions.indexOf(permission) >= 0);
}
I notice that (1) the output to console is what I expect it to be, and (2), I'm not getting the error, and my menu structure dynamically builds as expected...
so I'm a bit confused to say the least...
authorization.permissions is updated each time a user authenticates, logs out, or chooses another account to work on; in these cases we fetch updated permissions from the server and commit it to the store, so we can build our menu structure based on up-to-date permissions. Works pretty good, but I'm not sure I understand why this fails to be honest.
The plugin is created as follows in the install:
Vue.prototype.$security = new Vue(
...
methods: {
hasPermission: function(permission) {
...
}
}
...
);

How to use module.exports and requireJS?

im quite a noob in html and js, so forgive me if this is a dumb question but, im trying to use requireJs to export modules in node and i can't get the function work right.
here is the code extracted from example.
first i have this main.js, as the note in the documentation says http://requirejs.org/docs/node.html#2
var sayHi = require(['./greetings.js'], function(){});
console.log(sayHi);
and a greetings.js who export the answer
module.exports= 'Hello';
});
and get nothing as result, so i define the exports and modules
define( function(exports,module){
module.exports= 'Hello';
});
and get as result:
function localRequire()
what am i doing wrong? i read the documentation and examples, but somehow i can't make this works.
I'm assuming the require call you are using is RequireJS's require call, not Node's require. (Otherwise, you'd get a very different result.)
You are using the asynchronous form of the require call. With the asynchronous form, there is no return value for you to use, you have to use the callback to get module values, like this:
require(['./greetings.js'], function(sayHi){
console.log(sayHi);
});
However, because you are running in Node, you can do this:
var sayHi = require('./greetings.js');
Note how the first argument is a string, not an array of dependencies. This is the synchronous form of the require call. The returned value is the module you required. When you are in Node, RequireJS allows you to call this synchronous form anywhere. When you are running the browser, it is only available inside a define call.

Is it possible to use dojo/text! in an Intern functional test?

Is it possible to use "dojo/text!" in an Intern functional test?
I am able to setup my test page as a JSON string, but ideally I'd like to externalise the string in a file for ease of editing. I'm just getting started with Intern at the moment so I'm just experimenting with what's possible, but here is the start of my test code).
This works with the commented "testData" variable used, but is currently failing when I try to provide the same String by the dojo/text! statement.
Code:
define([
'intern!object',
'intern/chai!assert',
'dojo/text!./firstTestPageConfig.json',
'require'
], function (registerSuite, assert, PageConfig, require) {
registerSuite({
name: 'firstTest',
'greeting form': function () {
var testData = PageConfig;
// var testData = '{"widgets":[{"name":"alfresco/menus/AlfMenuBar","config":{"widgets":[{"name":"alfresco/menus/AlfMenuBarPopup","config":{"id":"DD1","label":"Drop-Down","iconClass":"alf-configure-icon","widgets":[{"name":"alfresco/menus/AlfMenuGroup","config":{"label":"Group 1","widgets":[{"name":"alfresco/menus/AlfMenuItem","config":{"label":"Item 1","iconClass":"alf-user-icon"}},{"name":"alfresco/menus/AlfMenuItem","config":{"label":"Item 2","iconClass":"alf-password-icon"}}]}},{"name":"alfresco/menus/AlfMenuGroup","config":{"label":"Group 2","widgets":[{"name":"alfresco/menus/AlfMenuItem","config":{"label":"Item 3","iconClass":"alf-help-icon"}}]}}]}}]}}]}';
var testPage = 'http://localhost:8081/share/page/tp/ws/unittest?testdata=';
return this.remote
.get(testPage + testData)
.waitForElementByCssSelector('.alfresco-core-Page.allWidgetsProcessed', 5000)
.elementById('DD1')
.clickElement()
.end()
}
});
});
The error I'm getting is this:
/home/dave/ScratchPad/ShareInternTests/node_modules/intern/node_modules/dojo/dojo.js:742
throw new Error('Failed to load module ' + module.mid + ' from ' + url +
^
Error: Failed to load module dojo/text from /home/dave/ScratchPad/ShareInternTests/dojo/text.js (parent: dojo/text!17!*)
at /home/dave/ScratchPad/ShareInternTests/node_modules/intern/node_modules/dojo/dojo.js:742:12
at fs.js:207:20
at Object.oncomplete (fs.js:107:15)
I've tried playing around with the loader/package/map configuration but without any success. It's not clear (to me at least) from the error message whether or not it can't find the file I'm passing to dojo/text (but I've tried full as well as relative paths) or the Dojo module itself ?
I'd just like to confirm that what I'm attempting is possible, before I spend any more time with this... but obviously any solution or example would be greatly appreciated!!
Many thanks,
Dave
To your specific error: You need to install Dojo for your own project if you want to use it. You are trying to load a module that does not exist. You may also try using the copy that comes with Intern, by loading modules from intern/dojo, but this isn’t recommended if you don’t understand the potential caveats of loading this internal library.
To using dojo/text in a functional test, generally: This is not currently possible unless you use the Geezer branch or explicitly use the Dojo 1 loader, because that module relies on functionality that is only exposed by the Dojo 1 loader when running in Node.js. A different text loader module that is fully generic would work, or you could load intern/dojo/node!fs and load the text yourself. This will be addressed in the future.
I just came across the same issue and for me this worked:
define([
"dojo/_base/declare",
"intern/dojo/text!/[PathToText]"
], function (declare, base) {
Seems as if Sitepen has included this in the meantime...

Gradle / Groovy properties

I would like to control 'global' config in Gradle build scripts using external property files on each build machine (dev, ci, uat,...) and specify the filename with a command line argument.
e.g. gradle -DbuildProperties=/example/config/build.properties
I specifically don't want to use gradle.properties as we have existing projects that already use this approach and (for example) we want to be able to amend database urls and jdbc drivers without having to change every project.
So far have tried:-
Properties props = new Properties()
props.load(new FileInputStream("$filename"))
project.setProperty('props', props)
which works but has a deprecated warning, but I can't figure out how to avoid this.
Have also tried using groovy style config files with ConfigSlurper:-
environments {
dev {
db.security {
driver=net.sourceforge.jtds.jdbc.Driver
url=jdbc:someserver://somehost:1234/some_db
username=userId
password=secret
}
}
}
but the colons and forward slashes are causing exceptions and we don't want to have to mess up config with escape characters.
There must be a non-deprecated way to do this - can anyone suggest the 'right' way to do it?
Thanks
You can get rid of the deprecated warning quite easily. The message you got probably looks something like this:
Creating properties on demand (a.k.a. dynamic properties) has been deprecated and is scheduled to be removed in Gradle 2.0. Please read http://gradle.org/docs/current/dsl/org.gradle.api.plugins.ExtraPropertiesExtension.html for information on the replacement for dynamic properties.
Deprecated dynamic property: "props" on "root project 'private'", value: "true".
It can be fixed by replacing:
project.setProperty('props', props)
with
project.ext.props = props
Just to supplement the response given by #Steinar:
it's still possible to use next syntax:
project.ext.set('prop_name', prop_value)
in case you have several properties from file:
props.each({ project.ext.set(it.key, it.value)} )