I am using the vue-webpack template and I have created a settings.json file to store environment variables that should be changed when installing the script.
My settings.json (just store the absolute path to the API server):
{
"apiURL": "//localhost/app/server/API"
}
How can I keep the file from being minified/bundled in the production version such that I can change it and the updated file will be used next time the app is accessed (without having to build it again) ?
In my app I use this file via require:
const SETTINGS = require('../settings.json');
I understand that by requireing it webpack will bundle it as a module, but how can I include it in my app such that the settings file will still be a separated file in the production build that I can edit.
Is there a better format/way to store those settings (so that they can be edited in production without re-building) ?
You can define those settings in an object that can be referenced in the externals configuration in webpack.config.js.
The externals configuration option provides a way of excluding
dependencies from the output bundles. Instead, the created bundle
relies on that dependency to be present in the consumer's environment.
Example:
externals: {
appSettings: "appSettings",
"window.appSettings": "appSettings"
}
Where appSettings is a global variable containing the environment variables you want to manipulate.
Alternatively, if you do not like that method that exposes the settings in the global object, you can do the following:
Export a variable with the default settings, which will be included in webpack bundle.
export var appSettings = {
currentSettings: "",
settings: {},
getString: function(strName) {
var sett = this.currentSettings ?
this.settings[this.currentSettings] :
appDefaultStrings;
if (!sett || !sett[strName]) sett = appDefaultStrings;
return sett[strName];
},
getSettings: function() { //Gets all available settings
var res = [];
res.push("");
for (var key in this.settings) {
res.push(key);
}
res.sort();
return res;
}
};
export var appDefaultStrings = {
apiURL: "//localhost/app/server/API"
//...
}
appSettings.settings["default"] = appDefaultStrings;
You can then require or import this variable and use it like so:
import appSettings from "../path/to/appSettings";
appSettings.getString("apiURL"); //"//localhost/app/server/API"
Now that you have your default settings up and running, we will create another file containing the custom settings.
import appSettings from "../path/to/appSettings";
export var appProductionSettings = {
apiUrl: "http://example.com"
//...
}
appSettings.settings["production"] = appProductionSettings;
The last thing you need to do is handle which settings you want to use. I have not used vue.js yet, but hopefully this will lead you in the right direction:
import appSettings from "../path/to/appSettings";
export class MyApp {
constructor() {
this.settingsValue = "";
}
get settings() {
return this.settingsValue;
}
set settings(value) {
this.settingsValue = value;
appSettings.currentSettings = value;
}
}
Change the settings:
import "../path/to/productionSettings";
var app = new MyApp();
app.settings = "production";
With this method you can create and use as many settings files as you want.
Related
I created a plugin, which should post some data to my backend. I tried to set up some backend url config. I checked the URl within my plugin with "console.log(...)" as u can see withn my code (in sendDataToBackEnd.js). But i getting following output "undefined".This is the error: "Error message: Cannot read property 'backEndUrl' of null"
Project structure:
project1
public
backend-config.js
faviocon.ico
index.html
src
App.vue
main.js
config
backEndUrlConfig.js
plugin
sendDataToBackEnd.js
Therefore I created backend-config.js within in Folder "public"
(function (window) {
window._backendconfig = {
urlBackend: `http://localhost:8090/api/auth/event`,
}
}(this));
My config.js looks like this:
export default { ...window._backendconfig }
And my PLugin "sendDataToBackEnd.js" looks like this:
import url from '../../config/backendURLconfig';
var backEndUrl = url.urlBackend;
console.log(backEndUrl)
const sendDatatoBackEnd = {}
sendDataToBackEnd.install = function (Vue){
{Method to send Data to my Backend}
}
export default sendDatatoBackEnd;
You're mixing using global scope JS (setting a property on window) in your config file with module style JS in your sendDataToBackEnd.js file (importing and exporting from modules).
You either need to export something from config (best option if you're using modules), or just access it from the window.
backendURLconfig.js
const config = {
urlBackend: `http://localhost:8090/api/auth/event`,
}
export default config
sendDataToBackEnd.js
import config from '../config/backendURLconfig';
var backEndUrl = config.urlBackend;
console.log(backEndUrl)
const sendDatatoBackEnd = {}
vuePlugin.install = function (Vue){
{Method to send Data to my Backend}
}
export default sendDatatoBackEnd;
AWS QLDB CreateLedger.js throwing error.
~repo/amazon-qldb-dmv-sample-nodejs$ node dist/CreateLedger.js
[LOG][Node.js QLDB Sample Code] Creating a ledger named: vehicle-registration...
[AWS qldb undefined 0.005s 0 retries] createLedger({ Name: 'vehicle-registration', PermissionsMode: 'ALLOW_ALL' })
[ERROR][Node.js QLDB Sample Code] Unable to create the ledger: ConfigError: Missing region in config.
How to update region in nodejs Typescript code in CreateLedger.js
https://docs.aws.amazon.com/qldb/latest/developerguide/getting-started.nodejs.step-1.html
I want to add region in CreateLeger.TS file
import { QLDB } from "aws-sdk";
import {
CreateLedgerRequest,
CreateLedgerResponse,
DescribeLedgerRequest,
DescribeLedgerResponse,
} from "aws-sdk/clients/qldb";
import { LEDGER_NAME } from "./qldb/Constants";
import { error, log } from "./qldb/LogUtil";
import { sleep } from "./qldb/Util";
const LEDGER_CREATION_POLL_PERIOD_MS = 10000; const ACTIVE_STATE =
"ACTIVE";
export async function createLedger(ledgerName: string, qldbClient:
QLDB): Promise<CreateLedgerResponse> {
log(`Creating a ledger named: ${ledgerName}...`);
const request: CreateLedgerRequest = {
Name: ledgerName,
PermissionsMode: "ALLOW_ALL"
}
const result: CreateLedgerResponse = await
qldbClient.createLedger(request).promise();`enter code here`
log(`Success. Ledger state: ${result.State}.`);
return result; }
In which section I can add the region. So generated
dist/createLedger.js file have the changes
You can set the region in your JavaScript code using the Global Configuration Object. Update the AWS.Config global configuration object as shown here:
AWS.config.update({region: 'us-east-1'});
Alternatively, you could set an environment variable in your shell:
export AWS_REGION=us-east-1
You can find all options in Setting the AWS Region.
After some try I got the answer.
you can update config in this file ~src/qldb/logutil.ts
import { config } from "aws-sdk";
config.logger = console;
config.update({region: 'us-east-1'});
One note on this: The node.js SDK doesn't by default load the shared config file which stores your region configuration among other things. I've found this confusing at times since some of the other SDKs e.g. boto3 do that by default.
You have to set the environment variable AWS_SDK_LOAD_CONFIG=1 to load it.
This shared config file is created e.g. when you go through the aws configure steps in the aws-cli.
Related posts:
How to Load config from ~/.aws/config
I am new to Ember, and am trying to use a global variable in the config / environment file to then import it into several adapters and models. I need this to change the variable in one place, instead of editing each file.
In this case, the global variable is a string with the address of the api server. The variable is named apiRoot. I tried to use the following configuration, but it does not work. Please tell me what needs to be done, if this is possible in the Ember, or maybe there is another way? Thanks for any help!
Environment File:
'use strict';
module.exports = function(environment) {
let ENV = {
modulePrefix: 'front',
environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
},
EXTEND_PROTOTYPES: {
Date: false
}
},
APP: {
}
};
if (environment === 'development') {
}
if (environment === 'test') {
ENV.locationType = 'none';
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
ENV.APP.autoboot = false;
}
if (environment === 'production') {
}
ENV.apiRoot = 'http://localhost:5555/api';
return ENV;
};
Adapter:
import RESTAdapter from '#ember-data/adapter/rest';
import ENV from '../../config/environment';
export default RESTAdapter.extend({
host: ENV.apiRoot,
pathForType() {
return "posts";
}
});
The problem is that your relative path probably refers to the /config/environment file outside of your appfolder. But it should refer to config/environment inside your app folder, a file that does not exist in your filesystem!
The reason for that is that you are not importing the config/environment file from the file system. Because that file does not exist in the browser. Instead ember-cli will execute that file during build time and send only the resulting JSON to your browser an make it avaliable at config/environment. But for all path in the browser the app folder is the root of your project. You can not import something outside the app folder.
And so your config/environment JSON that ember-cli produced will be basically moved into the app folder.
main.js has this code
window.l = function () { }
try {
window.l = console.log.bind(console)
} catch (e) { }
which works in non-Vue apps. However, when calling
l("test")
from a Vue action/method, it complains it isn't defined.
How can that work?
Reasoning: need to output some debugging data, with as less typing as possible.
When you want to add global-level functionalities to Vue, you should generally use mixins or plugins.
For the next examples, I assume you are using vue-cli with the complete webpack template. Moreover, we will use App.vue as a practical reference, but you can apply the same principles to other components...
Mixins
Create a mixin named log.js (in a mixins folder) with the following code:
export default {
methods: {
l (...args) { // rest parameters
console.log(...args) // spread operator
}
}
}
Open App.vue, import your mixin and use it:
<script>
import log from './mixins/log'
export default {
name: 'app',
mixins: [log],
created () {
this.l('Foo', 'Bar') // Foo Bar
}
}
</script>
Plugins
Create a plugin named log.js (in a plugins folder) with the following code:
export default {
install (Vue, options) {
Vue.prototype.$l = console.log.bind(console)
Vue.l = console.log.bind(console)
}
}
Open your main.js and declare your global plugin:
import log from './plugins/log'
Vue.use(log)
Open App.vue, import Vue and use your plugin:
<script>
import Vue from 'vue'
export default {
name: 'app',
created () {
this.$l('Foo') // Foo
Vue.l('Bar') // Bar
}
}
</script>
You might say: "Hey, why should I have to write this or Vue? I just wanna write l, that's all!". Well... This is actually how Vue has been designed. In order to provide global functionalities (shared by all components), you have to add static properties to the Vue object or prototype properties (Vue.prototype) that are accessible through this in Vue instances.
EDIT
I have just thought about an alternative solution...
You can edit your index.html to add this:
<script>
var l = console.log.bind(console)
</script>
Then, to avoid ESLint errors, you should also edit your .eslintrc.js file to reference your new global variable:
globals: {
l: true
}
The file looks like this:
// http://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
globals: {
l: true
},
env: {
browser: true,
},
// https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
extends: 'standard',
// required to lint *.vue files
plugins: [
'html'
],
// add your custom rules here
'rules': {
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 0,
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
}
}
Restart your dev server. Now you should be able to use l in your code:
<script>
export default {
name: 'app',
created () {
l('It works!')
}
}
</script>
Assign console.log like this.
window.l=console.log;
Get request by Systemjs is not adding extention .js to the url.
These are my TypeScript Classes
customer.ts
import {Address} from "./Address";
export class Customer {
private _customerName: string = "";
public CustomerAddress: Address = new Address();
public set CustomerName(value: string) {
if (value.length == 0) {
throw "Customer Name is required";
}
this._customerName = value;
}
public get CustomerName() {
return this._customerName;
}
Validate(): boolean {
return this._customerName != '';
}
}
address.ts
export class Address {
public Street1: string = "";
}
using following Systemjs init code
System.config({
defaultExtension: 'js',
});
System.import("Customer.js").then(function (exports) {
var cust = new exports.Customer();
});
Customer.js is loaded successfully but Address.js is not.
The GET request for Address.js does not contains .js extention
resulting following request in console
GET http://localhost:65401/Address 404 (Not Found).
I have tried to update following code in customer.ts to following
import {Address} from "./Address.js";
But it is syntactically wrong and it shows error in VS2013.
How can i force Systemjs to add extension ".js" to the GET request.
Thanks
The defaultExtension keyword is not a top level config option. It needs to be under packages directive, see: https://github.com/systemjs/systemjs/blob/master/docs/config-api.md#packages
That's why it's ignored and SystemJS doesn't append the extension. You can define one "global" package which is probably the easiest way to make sure the extension is always appended to every import path:
SystemJS.config({
packages: {
'.': {
defaultExtension: 'js'
}
}
});