How to pass environment value from npm to wdio file - webdriver-io

I wanted to pass the test environment value from command line with npm command which should be accessible into wdio.conf file. Something like npm test --env='stage'.
How to achieve it.

I do not think there is direct way in WDIO to achieve it. The one option that we used is:
Defined the below in the wdio.conf.js file:
const testEnv = process.env.TEST_ENV || 'FIT'; //code to read the value from cmd
exports.config = {
....
beforeSession: function(){
global.testEnv = testEnv; //making the testEnv global
}
....
}
Command to start the test: TEST_ENV='stag' npm test
So in your project the variable testEnv would be available throughout.

You can do it like this:
if (process.argv !== undefined && process.argv.length) {
process.argv.forEach(arg => {
if (arg.indexOf('--env=') !== -1) {
process.env.env = arg.replace('--env=', '');
}
});
}
console.log("Environment : " + process.env.env)
},

Related

How to use dotenv in SvelteKit project?

I'm trying to use dotenv.config() in a SvelteKit project.
I can run npm run build successfully. But when I try to start the server (using node build), it throws Error: Dynamic require of "fs" is not supported.
I tried to comment out the dotenv part in src/routes/test.js and build again, and this time the server started without any errors. (I created the project with npm init svelte#next without typescript, and except for the codes here, nothing else is changed)
How should I use dotenv here to load environment variables at runtime?
svelte.config.js
import node from '#sveltejs/adapter-node';
const config = {
kit: {
adapter: node(),
target: '#svelte'
}
};
export default config;
/src/routes/test.js
import dotenv from 'dotenv';
dotenv.config();
export function get() {
return {
body: {
test: process.env.TEST
}
}
}
.env
TEST=123
No need to explicitly load dotenv.
Vite uses dotenv
https://vitejs.dev/guide/env-and-mode.html#env-files
You can access your variable via import.meta.env.VITE_MY_VAR
Important is that your env variables must be prefixed with VITE_ in order to get them exposed. And if you are already running npm run dev, quit it and start again.
That worked for me.
Since a few weeks SvelteKit has a built-in way to handle environment variables:
https://kit.svelte.dev/docs/modules#$env-dynamic-private
I solved the problem with env-cmd (https://www.npmjs.com/package/env-cmd) by adding env-cmd to the beginning of svelte-kit dev, svelte-kit preview and node build.
Also, use process.env['TEST'] instead of process.env.TEST since process.env.TEST is replaced with ({}) by vite. (https://github.com/vitejs/vite/issues/3176)
This is what I did:
vite has a special config option for server port.
// import adapter from '#sveltejs/adapter-static';
import adapter from '#sveltejs/adapter-node';
import preprocess from 'svelte-preprocess';
import path from 'path';
import dotenv from 'dotenv-flow';
dotenv.config();
/** #type {import('#sveltejs/kit').Config} */
const config = {
// Consult https://github.com/sveltejs/svelte-preprocess
// for more information about preprocessors
preprocess: preprocess(),
kit: {
// hydrate the <div id="svelte"> element in src/app.html
// target: '#svelte',
/*
adapter: adapter({
// default options are shown
pages: 'build',
assets: 'build',
fallback: 'index.html'
}),
*/
adapter: adapter({
out: './build',
precompress: true
}),
vite: {
resolve: {
alias: {
$components: path.resolve('./src/components'),
$stores: path.resolve('./src/stores'),
$api: path.resolve('./src/api')
}
},
build: {
minify: true
},
server: {
port: process.env.PORT || 3000
}
}
}
};
export default config;
I have .env for defaults (dev etc) and .env.local that is ignored in .gitignore for production (keys, etc).
When .env.local is present it uses that port.
edit: this does not work with node-adapter in production. I think we need to declare PORT some other way. it only works with npm run dev

rollup custom cli arguments for the config throwing errors

I have an app in progress which requires 3 micro code bases and some iframe postMessage stuff.
Controlling the build of all these i aim to manage from a single rollup config file and injecting arguments in via cli:
"scripts": {
"dev:child": "rollup -c rollup.config.js -w --for_type child",
"dev:parent": "rollup -c rollup.config.js -w --for_type parent",
"dev:sidebar": "rollup -c rollup.config.js -w --for_type sidebar",
My rollup config works but the issue is that rollup complains that for_type is a non recognised argument.
What is the proper way of injecting custom arguments to rollup?
I cannot see anything here: https://rollupjs.org/guide/en/#configuration-files
When you export a function instead of an object in rollup.config.js, the first argument of the function will be a CLI arguments object. For example, if you config is:
export default cliArgs => {
let build = {
input: 'src/index.js',
output: [/* ... */],/
plugins: [/* ... */]
};
switch (cliArgs.for_type) {
case 'child':
// Customise build for child
break;
case 'parent':
// Customise build for parent
break;
case 'sidebar':
// Customise build for sidebar
break;
default:
// No CLI argument
break;
}
return build
};
Have another look at the documentation for more info.
From https://rollupjs.org/guide/en/#configuration-files
You can even define your own command line options if you prefix them with config:
export default commandLineArgs => {
if (commandLineArgs.configDebug === true) {
return debugConfig;
}
return defaultConfig;
};

Custom global process.env variable with Webpack build

I have a Vue application that's compiled using Webpack. I'm trying to add a variable into the 'npm run dev' command that I can then use globally throughout the project. Currently, I am running 'npm --brand=foo run dev' and consoling 'process.env.brand' in the build.js file returns 'foo'. Now I need to make this available to the rest of the project. Here is my setup:
WEBPACK.DEV.CONF.JS
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
module.exports = merge(baseWebpackConfig, {
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
})
})
DEV.ENV.JS
var merge = require('webpack-merge')
var prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})
File structure is Build/build.js + webpack.dev.conf.js and Config/dev.env.js. I tried to add a 'brand' property like the following, but process.env.brand was undefined in this file.
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
brand: process.env.brand
})
UPDATE by #Linx to pass the argument dynamically directly from
command line
Run the command and pass in the variable like: npm --brand=foo run dev
Then, variable is then available in the webpack config file as
process.env.npm_config_brand.
Another option is to setting the variable inside the npm script section:
package.json
{
//...
"scripts": {
"dev": "SET brand=foo& webpack -p"
},
If you are using linux, maybe you should remove the SET --> "dev": "brand=foo& webpack -p"
Then run the command like: npm run dev
In both cases, to make it available for the rest of the project you can use webpack.DefinePlugin
module.exports = {
//...
plugins: [
new webpack.DefinePlugin({
'__BRAND__': process.env.brand,
})
]
}
The variable will be accessible in the rest of the project like: console.log(__BRAND__);

Cross platform NPM start script

I'm building out an Electron app that will be developed by folks on both Windows and OS X. I'd like to create a cross-platform start script. So far, I've had exactly zero luck getting something that works. The issue, I think, is that I need to set the NODE_ENV environment variable and the syntax is slightly different.
I'm hoping there's a way that I just haven't found yet. My current scripts section follows:
"scripts": {
"start:osx": "NODE_ENV=development electron ./app/",
"start:win": "set NODE_ENV=development && electron ./app/"
}
I'd really like to create a single "start" script and eliminate the platform-specific variants. Is it possible?
Environment variables are a problem in Windows.
As stated Domenic Denicola (one of the main contributors to npm) :
This is not npm's job. You can run custom Node scripts to set environment variables using process.env if you'd like, or use something that isn't environment variables (like JSON).
...
You can write custom scripts to work around connect's limitations, e.g. in your tests modify process.env.
(Reference : this issue)
So we'll manage through a JS script (Solution inspired on this commit) :
Create a exec.js file in a scripts directory
Copy the following code in exec.js :
var exec = require('child_process').exec;
var command_line = 'electron ./app/';
var environ = (!process.argv[2].indexOf('development')) ? 'development' : 'production';
if(process.platform === 'win32') {
// tricks : https://github.com/remy/nodemon/issues/184#issuecomment-87378478 (Just don't add the space after the NODE_ENV variable, just straight to &&:)
command_line = 'set NODE_ENV=' + environ + '&& ' + command_line;
} else {
command_line = 'NODE_ENV=' + environ + ' ' + command_line;
}
var command = exec(command_line);
command.stdout.on('data', function(data) {
process.stdout.write(data);
});
command.stderr.on('data', function(data) {
process.stderr.write(data);
});
command.on('error', function(err) {
process.stderr.write(err);
});
Update your package.json :
"scripts": {
"start": "node scripts/exec.js development",
}
Run npm script : npm run start
Edit 05.04.2016
There is a very useful npm package that allows manages this problem : cross-env. Run commands that set environment variables across platforms

How to set protractor(v1.4.0) baseUrl using protractor API instead of configuration file?

i use protractor v1.4.0 and I want to set protractor baseUrl from command line so i can't use
baseUrl: 'http://localhost:8000/',
config option in protractor configuration file. I want to define default value for base url with "params" option in protractor configuration file as follows:
params: {
baseUrl: 'http://localhost:8080/'
},
and then overwrite the default value by passing a new value from command line when i run protractor as follows:
protractor 'path_to_my_conf_file' --params.baseUrl http://localhost:80/
then in my spec file i need to set base url using protractor API, but i can't find how to do that.
The 1-st answer to the following question is exactly what i need but it doesn't work.
How can I add URL's dynamically to Protractor tests?
As another option, could also try browser.baseUrl = "https://test-url.com" in onPrepare (works in Protractor 1.4.0)
You can just change it from the command line like so:
protractor --baseUrl http://whateveryouwant
Run tests via grunt with grunt-protractor-runner and grunt-option libraries:
protractor: {
options: {
configFile: "path_to_my_conf_file",
args: {
baseUrl: grunt.option('baseUrl', 'http://localhost:80/')
}
}
}
Then, run the task via:
grunt protractor --baseUrl=http://mynewurl
And, to let it use the default baseUrl, just run:
grunt protractor
Use gulp for your test run; shown below is the gulpfile.js
var gulp = require('gulp');
var runSequence = require('run-sequence');
var protractor = require('gulp-protractor').protractor;
gulp.task('protractor', function() {
var configFile = 'test/e2e/protractor-config.js';
return gulp
.src(['./test/e2e/spec/sample.js'])
.pipe(protractor({
configFile: configFile,
args: ['--baseUrl', 'http://www.google.com']
}))
.on('error', function(e) { throw e; });
});
gulp.task('test', function(callback) {
runSequence(
'protractor',
callback
);
});
Task run:
gulp test