Gulp Clean is triggered when commandline arguments passed into gulp task - sharepoint

I have the following gulp task:
build.task('upload', {
execute: (config) => {
/*
THIS WORKS, BUT ONLY if i do "gulp upload".
"gulp upload -u < commandline options >" fails.
const uname = "johndoe#asdf.com";
const pwd = "supersecret";
const siteUrl = "https://<mytenant>.sharepoint.com/sites";
const siteCatalogUrl = "https://<mytenant>.sharepoint.com/sites/CatalogSiteName";
const catalogName = "AppCatalog";
console.log(uname);
console.log(siteUrl);
console.log(siteCatalogUrl);
console.log(catalogName);
*/
const uname = config.args['u'];
const pwd = config.args['p'];
const siteUrl = config.args['sU'];
const siteCatalogUrl = config.args['cU'];
const catalogName = config.args['c'];
console.log(uname);
console.log(siteUrl);
console.log(siteCatalogUrl);
console.log(catalogName);
return new Promise((resolve, reject) => {
const pkgFile = require('./config/package-solution.json');
const folderLocation = `./sharepoint/${pkgFile.paths.zippedPackage}`;
return gulp.src(folderLocation)
.pipe(spsync({
"username": uname,
"password": pwd,
"site": siteCatalogUrl,
"libraryPath": catalog,
"publish": true
}))
.on('finish', resolve);
});
}
});
when I'm testing on the command line, i run this like this:
gulp upload
the first thing it does call gulp clean ... which blows away the sppkg. So the upload task fails.
The other artifact that I've noticed, which I can't explain is that when I run the gulp task, i see this:
Build target: SHIP
instead of the usual
Build target: DEBUG
Output
lab3:search-parts admin$ gulp upload
Build target: SHIP
[14:16:31] Using gulpfile /src/search/gulpfile.js
[14:16:31] Starting 'upload'...
[14:16:31] Starting gulp
[14:16:31] Starting subtask 'clean'...
[14:16:31] Finished subtask 'clean' after 119 ms
[14:16:31] The following tasks did not complete: upload
[14:16:31] Did you forget to signal async completion?
About to exit with code: 0
Process terminated before summary could be written, possible error in async code not continuing!
Trying to exit with exit code 1
Dunno if it's related, but sharing in case...
Thanks.
EDIT 1
I can consistently recreate the problem, and I found a fix too - albeit - not one that i can use in production. But I don't know what the root cause of the issue is yet.
To create the problem I simply need to pass in the arguments via the config object. In other words, I trigger this gulp method via command line like this:
gulp package-solution --ship
gulp upload --u "johndoe#asdf.com" --p "supersecret" --sU "https://<mytenant>.sharepoint.com/sites/CatalogSiteName" --cU "https://<mytenant>.sharepoint.com/sites/CatalogSiteName" --c "AppCatalog"
When I run the script, the first thing it does is a gulp clean.
If i comment out all the logic to grab the variables from the config.args[] and just use the hardcoded values... it works. But I have to make sure that I don't supply the arguments via the commandline. So in other words, this works:
lab3:spparts admin$ gulp upload
Build target: DEBUG
[14:27:27] Using gulpfile /src/sp/spparts/gulpfile.js
[14:27:27] Starting 'upload'...
[14:27:27] Starting gulp
johndoe#asdf.com
https://<mytenant>.sharepoint.com/sites/CatalogSiteName
https://<mytenant>.sharepoint.com/sites/CatalogSiteName
AppCatalog
[14:27:27] Uploading spparts.sppkg
[14:27:32] Upload successful 5289ms
[14:27:35] Published file 2408ms
[14:27:35] Finished 'upload' after 7.73 s
[14:27:35] ==================[ Finished ]==================
[14:27:36] Project spparts version:4.3.0
[14:27:36] Build tools version:3.17.11
[14:27:36] Node version:v10.24.1
[14:27:36] Total duration:13 s
But this doesn't: (eventhough the js code is still using hardcoded values)
lab3:spparts admin$ gulp upload --u "johndoe#asdf.com" --p "supersecret" --sU "https://<mytenant>.sharepoint.com/sites/CatalogSiteName" --cU "https://<mytenant>.sharepoint.com/sites/CatalogSiteName" --c "AppCatalog"
Build target: SHIP
[14:27:27] Using gulpfile /src/sp/spparts/gulpfile.js
[14:27:27] Starting 'upload'...
[14:27:27] Starting gulp
[14:30:36] Starting subtask 'clean'...
[14:30:36] Finished subtask 'clean' after 68 ms
johndoe#asdf.com
https://<mytenant>.sharepoint.com/sites/CatalogSiteName
https://<mytenant>.sharepoint.com/sites/CatalogSiteName
AppCatalog
[14:30:36] 'upload' errored after 85 ms
[14:30:36] Error: File not found with singular glob: /src/spparts/sharepoint/solution/spparts.sppkg (if this was purposeful, use `allowEmpty` option)
So in summary, I think I can say when I pass in command line arguments, the script calls gulp clean. But I don't know why.
In case it helps, here's my version information:
lab3:spparts admin$ gulp -v
CLI version: 2.3.0
Local version: 4.0.2
version of sp-build-web is 1.12.1

I take it the upload task uploads the package to the [tenant|site collection] app catalog? This doesn't solve your problem in the post, but have you considered using the CLI for Microsoft 365? It's got a command that does this for you.
Best of all, there's no code to add to your project's gulpfile.js or code to maintain. Works great... using three commands you (1) login, (2) upload, and (3) deploy (ie: trust) the package.
# Sign into Microsoft 365
m365 login ${{ m365_target_site_url }} --authType password --userName ${{ m365_user_login }} --password ${{ m365_user_password }}
displayName:
# Upload SharePoint package to Site Collection App Catalog
m365 spo app add --filePath ${{ sppkg_filepath }} --appCatalogUrl ${{ m365_target_site_url }}/AppCatalog --scope sitecollection --overwrite
# Deploy SharePoint package
m365 spo app deploy --name ${{ spPkgFileName}} --appCatalogUrl ${{ m365_target_site_url }} --scope sitecollection --skipFeatureDeployment

Related

Change Environmet Variables at runtime (React, vite) with docker and nginx

at work I need to make it possible to change the environmet variables at runtime, from an Azure web service, through docker and nginx.
I tried this, this and some similar solutions, but I couln't get any of them to work.
I also couldn't find any solution online or any article/thread/post that explained if this is even possible, I only always find the text that vite statically replaces the env variables at build time.
During our CI/CD pipeline vite gets the env variables but our Azure admins want to be able to configure them from Azure, just for the case of it.
Does anyone know if this is possible and or maybe has a solution or some help, please ? :)
It is not possible to dynamically inject Vite env variables. But what is possible, is to change the window object variables (assign them on runtime).
WARNING!!! DO NOT EXPOSE ANY SENSITIVE VARIABLES THROUGH THE WINDOW OBJECT. YOUR FRONT-END APPLICATION SOURCE IS VISIBLE TO ANYONE USING IT
Steps:
Create your desired env files and place them in <rootDir>/public. Let's call them env.js and env-prod.js.
Inside your env.js and env-prod.js You want to assign your desired variables using var keyword. Also, you will have to reference these values in your source like window.MY_VAR to be able to use them.
Create a script tag inside your <rootDir>/index.html like this:
<script type="text/javascript" src="./env.js"></script>.
IMPORTANT!!! type="text/javascript" is important, because if You specify module, Vite will include your env.js source inside your minified index.js file.
Vite config (optional):
plugins: [react(), tsConfigPath()],
build: {
emptyOutDir: true, // deletes the dist folder before building
},
});
How to serve the env files on runtime. Create a node server which will serve your frontend application. But before serving the env.js file, depending on our process.env.ENVIRONMENT you can now choose which env.js to serve. Let's say my node server file is stored at <rootDir>/server/server.js:
const express = require("express");
const path = require("path");
const app = express();
const env = process.env.ENVIRONMENT || "";
console.log("ENVIRONMENT:", env);
const envFile = path.resolve("public", env ? `env-${env}.js` : "env.js");
const indexFile = path.resolve("dist", "index.html");
app.use((req, res, next) => {
const url = req.originalUrl;
if (url.includes("env.js")) {
console.log("sending", envFile);
// instead of env.js we send our desired env file
res.sendFile(envFile);
return;
}
next();
});
app.use(express.static(path.resolve("dist")));
app.get("*", (req, res) => {
res.sendFile(indexFile);
});
app.listen(8000);
Serve your application build while running node ./server/sever.js command in your terminal.
Finally:
my env.js contains var RUNTIME_VAR = 'test'
my env-prod.js contains var RUNTIME_VAR = 'prod'
After I set my process.env.ENVIRONMENT to prod. I get this file served:
My Solution is that it schould work with the links from my question.
I use this approach and it works, the only thing that needs to be thought of is to use a different variable name/prefix (e.g. "APP_...") so vite doesn't change them at build time.
I created a config file wich resolves the variable, for example if the app is in production than it uses the new Variable "APP_.."(which comes injected from nginx/ docker) or use "VITE_..."-variable if "APP_.." is undefined.
I came up with a solution and published it as packages to the npm registry.
With this solution, you don't need to change any code:
// src/index.js
console.log(`API base URL is: ${import.meta.env.API_BASE_URL}.`);
It separate the build step out into two build step:
During production it will be statically replaced import.meta.env with a placeholder:
// dist/index.js
console.log(
`API base URL is: ${"__import_meta_env_placeholder__".API_BASE_URL}.`
);
You can then run the package's CLI anywhere to replace the placeholders with your environment variables:
// dist/index.js
console.log(
`API base URL is: ${{ API_BASE_URL: "https://httpbin.org" }.API_BASE_URL}.`
);
// > API base URL is: https://httpbin.org.
Here is the documentation site: https://iendeavor.github.io/import-meta-env/.
Feel free to provide any feedback.
First create .env file in project root,then define a variable in .env
e.g:VITE_APP_any = 'any'
and then add following line to vite.config.js :
export default defineConfig(({ command, mode }) => {
const env = loadEnv(mode, process.cwd(), ""); //this line
return {
.
.
.
For usage can use following line
import.meta.env.VITE_APP_any
Or
process.env.VITE_APP_any
here is the Dockerfile
FROM node:alpine3.14 AS buildJS
WORKDIR /var/www/html
COPY . .
RUN apk add --no-cache yarn \
&& yarn && yarn build
FROM nginx:stable-alpine
WORKDIR /var/www/html
COPY --from=buildJS /var/www/html/dist .
COPY ./docker/conf/nginx.conf /etc/nginx/conf.d/default.conf
COPY ./docker/conf/config.json /etc/nginx/templates/config.json.template
ENTRYPOINT []
CMD sleep 5 && mv /etc/nginx/conf.d/config.json config.json & /docker-entrypoint.sh nginx -g 'daemon off;'
I'm building the project in the first stage without any envs,
in the second stage I'm copying the files and then creating the config.json file based on envs that are passed at run time with envstub feature of nginx.
then from the project I called the config.json file and load the envs from there but be careful you can not import it because imports will be resolved at build time instead you have to get it with fetch or axios or any equivalents
You can set the variables in YAML format and update them accordingly as per your requirement.
Below is the sample YAML format which we use as a template:
#Set variables once
variables:
configuration: debug
platform: x64
steps:
#Use them once
- task: MSBuild#1
inputs:
solution: solution1.sln
configuration: $(configuration) # Use the variable
platform: $(platform)
#Use them again
- task: MSBuild#1
inputs:
solution: solution2.sln
configuration: $(configuration) # Use the variable
platform: $(platform)
Check this SO for more insights to understand environment variables hosted in azure web app

MeteorUp volumes and how Meteor can access to their contents

First, thank you for reading my question. This is my first time on stackoverflow and I made a lot of research for answers that could help me.
CONTEXT
I'm developing a Meteor App that is used as a CMS, I create contents and store datas in mongoDb collections. The goal is to use these datas and a React project to build a static website, which is sent to an AWS S3 bucket for hosting purpose.
I'm using meteorUp to deploy my Meteor App (on an AWS EC2 instance) and according to MeteorUp documentation (http://meteor-up.com/docs.html#volumes), I added a docker volume in my mup.js:
module.exports = {
...
meteor: {
...
volumes: {
'/opt/front': '/front'
},
...
},
...
};
Once deployed, volume is well set in '/opt/myproject/config/start.sh':
sudo docker run \
-d \
--restart=always \
$VOLUME \
\
--expose=3000 \
\
--hostname="$HOSTNAME-$APPNAME" \
--env-file=$ENV_FILE \
\
--log-opt max-size=100m --log-opt max-file=10 \
-v /opt/front:/front \
--memory-reservation 600M \
\
--name=$APPNAME \
$IMAGE
echo "Ran abernix/meteord:node-8.4.0-base"
# When using a private docker registry, the cleanup run in
# Prepare Bundle is only done on one server, so we also
# cleanup here so the other servers don't run out of disk space
if [[ $VOLUME == "" ]]; then
# The app starts much faster when prepare bundle is enabled,
# so we do not need to wait as long
sleep 3s
else
sleep 15s
fi
On my EC2, '/opt/front' contains the React project used to generate a static website.
This folder includes a package.json file, every modules are available in the 'node_modules' directory. 'react-scripts' is one of them, and package.json contains the following script line:
"build": "react-scripts build",
React Project
React App is fed with a JSON file available in 'opt/front/src/assets/datas/publish.json'.
This JSON file can be hand-written (so the project can be developed independently) or generated by my Meteor App.
Meteor App
Client-side, on the User Interface, we have a 'Publish' button that the Administrator can click when she/he wants to generate the static website (using CMS datas) and deploy it to the S3 bucket.
It calls a Meteor method (server-side)
Its action is separated in 3 steps:
1. Collect every useful datas and save them into a Publish collection
2. JSON creation
a. Get Public collection first entry into a javascript object.
b. Write a JSON file using that object in the React Project directory ('opt/front/src/assets/datas/publish.json').
Here's the code:
import fs from 'fs';
let publishDatas = Publish.find({}, {sort : { createdAt : -1}}).fetch();
let jsonDatasString = JSON.stringify(publishDatas[0]);
fs.writeFile('/front/src/assets/datas/publish.json', jsonDatasString, 'utf8', function (err) {
if (err) {
return console.log(err);
}
});
2. Static Website build
a. Run a CD command to reach React Project's directory then run the 'build' script using this code:
process_exec_sync = function (command) {
// Load future from fibers
var Future = Npm.require("fibers/future");
// Load exec
var child = Npm.require("child_process");
// Create new future
var future = new Future();
// Run command synchronous
child.exec(command, {maxBuffer: 1024 * 10000}, function(error, stdout, stderr) {
// return an onbject to identify error and success
var result = {};
// test for error
if (error) {
result.error = error;
}
// return stdout
result.stdout = stdout;
future.return(result);
});
// wait for future
return future.wait();
}
var build = process_exec_sync('(cd front && npm run build)');
b. if 'build' is OK, then I send the 'front/build' content to my S3 bucket.
Behaviors:
On local environment (Meteor running on development mode):
FYI: React Project directory's name and location are slightly different.
Its located in my meteor project directory, so instead of 'front', it's named '.#front' because I don't want Meteor to restart every time a file is modified, added or deleted.
Everything works well, but I'm fully aware that I'm in development mode and I benefit from my local environment.
On production environment (Meteor running on production mode in a docker container):
Step 2.b : It works well, I can see the new generated file in 'opt/front/src/assets/datas/'
Step 3.a : I get the following error:
"Error running ls: Command failed: (cd /front && npm run build)
(node:39) ExperimentalWarning: The WHATWG Encoding Standard
implementation is an experimental API. It should not yet be used in
production applications.
npm ERR! code ELIFECYCLE npm ERR! errno 1 npm
ERR! front#0.1.0 build: react-scripts build npm ERR! Exit status 1
npm ERR! npm ERR! Failed at the front#0.1.0 build script. npm ERR!
This is probably not a problem with npm. There is likely additional
logging output above.
npm ERR! A complete log of this run can be found in: npm ERR!
/root/.npm/_logs/2021-09-16T13_55_24_043Z-debug.log [exec-fail]"
So here's my question:
On production mode, is it possible to use Meteor to reach another directory and run a script from a package.json?
I've been searching for an answer for months, and can't find a similar or nearby case.
Am I doing something wrong?
Am I using a wrong approach?
Am I crazy? :D
Thank you so much to have read until the end.
Thank you for your answers!
!!!!! UPDATE !!!!!
I found the solution!
In fact I had to check few things on my EC2 with ssh:
once connected, I had to go to '/opt/front/' and try to build the React-app with 'npm run build'
I had a first error because of CHMOD not set to 777 on that directory (noob!)
then, I had an error because of node-sass.
The reason is that my docker is using Node v8, and my EC2 is using Node v16.
I had to install NVM and use a Node v8, then delete my React-App node_modules (and package-lock.json) then reinstall it.
Once it was done, everything worked perfectly!
I now have a Meteor App acting as a CMS / Preview website hosted on an EC2 instance that can publish a static website on a S3 bucket.
Thank you for reading me!
!!!!! UPDATE !!!!!
I found the solution!
In fact I had to check few things on my EC2 with ssh:
once connected, I had to go to '/opt/front/' and try to build the React-app with 'npm run build'
I had a first error because of CHMOD not set to 777 on that directory (noob!)
then, I had an error because of node-sass.
The reason is that my docker is using Node v8, and my EC2 is using Node v16.
I had to install NVM and use a Node v8, then delete my React-App node_modules (and package-lock.json) then reinstall it.
Once it was done, everything worked perfectly!
I now have a Meteor App acting as a CMS / Preview website hosted on an EC2 instance that can publish a static website on a S3 bucket.
Thank you for reading me!

Setting up Angular Universal App for development

I have created a project with Angular-CLI. (using command: ng new my-angular-universal).
Then I carefully followed all the instructions from https://github.com/angular/angular-cli/wiki/stories-universal-rendering
It builds for --prod and works fine. But there are no instructions on how I can set up a --dev build and have it served with --watch flag.
I tried removing --prod flags from npm "scripts", and it doesn't even run in dev mode. It builds fine but when I open it in browser this is what I see (directly printed to response):
TypeError: Cannot read property 'moduleType' of undefined
at C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:7069:134
at ZoneDelegate.invoke (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:105076:26)
at Object.onInvoke (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:6328:33)
at ZoneDelegate.invoke (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:105075:32)
at Zone.run (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:104826:43)
at NgZone.run (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:6145:69)
at PlatformRef.bootstrapModuleFactory (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:7068:23)
at Object.renderModuleFactory (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:52132:39)
at View.engine (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:104656:23)
at View.render (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:130741:8)
the versions of npm packages that I use are currently the latest:
#angular/* - #5.2.*
#angular/cli #1.7.3
except for ts-loader, had to downgrade it because it wasn't working:
ts-loader #3.5.0
So if anyone has any info on how to make this work, it would be very appreciated! Or maybe you know some project templates with Angular Universal App configured for both --dev and --prod builds and ability to --watch?
For development, run npm run start which triggers ng serve. The current setup has hot module reloading so it will watch for your changes and update your dev view. I used the same instructions and got it working here https://github.com/ariellephan/angular5-universal-template
In short, for development, run npm run start and look at http://localhost:4200.
For production, run npm run build:ssr and npm run serve:ssrand look at http://localhost:4000
As contributors have pointed out, it might not be the most efficient and fastest way to develop, but nevertheless I did not want to accept workarounds. Besides, hosting front and back on separate servers brings up CORS issues, and I never planned my app to run on separate hosts, I wanted it all on the same host together with API methods.
The problem with --dev build was this:
when building with the following command:
ng build --app 1 --output-hashing=false (note that there is no --prod flag)
AppServerModuleNgFactory turned out missing in the ./dist-server/main.bundle
I imagine that this relates to the ahead of time(--aot) compilation which is the default behavior if you are building for --prod. So the instructions from https://github.com/angular/angular-cli/wiki/stories-universal-rendering included instructions to configure express server for production build only. And since there is no need for server to be able to dynamically render html templates the working --dev build command would be:
ng build --app 1 --output-hashing=false --aot
and this gets rid of the TypeError: Cannot read property 'moduleType' of undefined
Now to watch this whole mess:
run these in separate command windows:
ng build --watch
ng build --app 1 --output-hashing=false --aot --watch
webpack --config webpack.server.config.js --progress --colors --watch
And for the server to restart on change, you have to install nodemon package and run it like this:
nodemon --inspect dist/server (--inspect if you wish to debug server with chrome)
Some other important stuff:
Angular/CLI has a command to generate necessary scaffolding for a universal app:
ng generate universal
and it generates a fixed version of main.ts that avoids client angular bootstrap issue:
document.addEventListener('DOMContentLoaded', () => {
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
});
a problem that I stumbled upon once I implemented TransferState
There are basically two parts - the server and the UI. While developing the UI, I simply use ng serve. That means when I make changes in my code in the IDE, the browser refreshes automatically. And, here the server part is not used.
I do prod build and run the server only for final testing to see if everything works as expected (No error due to any 3PP library DOM manipulation or AOT related issues, etc.)
Here, I have created a skeleton structure of an Angular Universal project. As I extensively use Vagrant and Docker in my projects, I run the server in a Docker container within the Vagrant guest system. And for development of the UI, I don't run the server. Simply, the ng serve is used.
If you look into my structure in the above Github link, you'll find the details as to how to run it for development and production in the Readme file.
The web server handler server.ts uses the server bundle
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main.bundle');
That's why the server bundle needs to be compiled before you can compile the server.ts file.
So having a watch system would mean
watching/recompiling the client bundle
watching/recompiling the server bundle
recompiling the server.ts once the server bundle is created
All of them take some time (especially if you do it with aot)
I'd recommend, like Saptarshi Basu mentionned, to develop as best as you can with ng serve and check with angular universal every so often.
Otherwise, it should be possible do achieve what you want with some kind of tasks (grunt/gulp/...) which triggers sequentially ng build ... and recompilation of server.ts file.
It is a bit messy no doubt, as we preferably wish for one command to rule them all.
I came up with a somewhat OK solution where my output will be:
dist/browser
dist/ng-server
Using the executable npm-run-all package (I find it working a lot better on windows machines than concurrently does) I run the three watch tasks: browser, ng-server and nodeJS. Watching node has a pre-task defined that simply runs a small utility/helper/file that watches for the existence of a dist/ng-server folder and terminate itself once found.
For all of this to work (based on the universal-starter repo as of november 2018) there's a couple of modifications to package.json required. Primarily, to support the --watch flag on ng run commands we need to update the compiler-cli (if memory serves), ng update --all should take care of that, giving you the latest angular/cli version in the process (assuming you have a recent cli version installed globally).
package.json
ng update --all
angular 6+
angular/cli 7+
yarn add/npm install the following
chokidar
npm-run-all
(runs our tasks in parallel with the -p flag. -p kills all processes, -l gives each running task a specific color and name in the console)
ts-node (runs nodejs in it's ts-format)
nodemon // for restarting ts-node
add something similar to my util/await-file.js (after some consideration I added my own file-watcher code below even though it wasn't exactly written with the intentions to be put up on display...)
modify your package.json scripts like below
modify your angular.json to match your folder names, following my examples, mainly the "server"'s outputPath should be changed from dist/server to dist/ng-server.
package.json scripts
"dev": "npm-run-all -p -r -l watch:ng-server watch:browser watch:node",
"watch:browser": "ng build --prod --progress --watch --delete-output-path",
"watch:ng-server": "ng run ng-universal-demo:server --watch --delete-output-path",
"watch:node": "yarn run watch:file-exist && yarn run ts-node",
"ts-node": "nodemon --exec ts-node server.ts -e ts,js",
"watch:file-exist": "node utils/await-file.js",
util/await-file.js
const chokidar = require('chokidar');
const fs = require('fs');
const path = require('path');
const DIR_NAME = 'ng-server';
const DIST_PATH = './dist';
// creates dist folder if it doesn't exist - prior to adding it to the watcher.
if (!fs.existsSync(DIST_PATH)) {
fs.mkdirSync(DIST_PATH);
}
const watcher = chokidar.watch('file, dir', {
ignored: '*.map',
persistent: true,
awaitWriteFinish: {
stabilityThreshold: 5000,
pollInterval: 100
}
});
const FOLDER_PATH = path.join(process.cwd(), 'dist');
watcher.add(FOLDER_PATH);
console.log(`file-watcher running, waiting for ${DIST_PATH}/${DIR_NAME}`);
function fileFound() {
console.log(`${DIR_NAME} folder found - closing`);
watcher.close();
process.exit();
}
watcher
.on('add', function (filePath) {
const matchWith = path.join('dist', DIR_NAME);
const paths = filePath.split(path.sep);
const fileName = paths[paths.length - 1];
if ((filePath.indexOf(matchWith) >= 0)
&& fileName.indexOf('.js') > fileName.length - 4) {
fileFound();
}
})
.on('error', error => console.log(`Watcher error: ${error}`));
"npm run start" and using "http://localhost:4200" works for me. Even with Angular 10

Protractor & Jasmine Configuration on Jenkins

I am trying to configure Protractor on Jenkins for CTI.... I have already setup Protractor along with Jasmine and trying to get it integrated with Jenkins.
I have gone through several links & blogs on internet but none seem to be helpful in providing detailed information on how to get the Protractor configured with Jenkins.
Any help or pointing towards the right blog or video will be really appreciated. Thanks
#Vishal
Please find the below snippet you can add as grunt task.
'use strict';
module.exports = function (grunt) {
grunt.initConfig({
exec: {
protractorRunAppsTest: {
cmd: 'C:\\Program Files\\nodejs\\node.exe C:\\Users\\Administrator\\AppData\\Roaming\\npm\\node_modules\\protractor\\built\\cli.js C:\\Jenkins\\workspace\\test\\conf.js'
}
},
server: {
port:3000,
base: ['app']
},
});
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-protractor-runner');
grunt.loadNpmTasks('grunt-run');
grunt.loadNpmTasks('grunt-exec');
grunt.registerTask('server', 'Start node server', function() {
grunt.log.writeln('Started server on port 3000');
require('./app.js');
});
grunt.registerTask('runAppsTest', ['exec:protractorRunAppsTest']);
};
Save the above code as Gruntfile.js
Make sure this is in the workspace folder for jenkins.
In Jenkins job add the 'Build' Section (i am assuming Jenkins is windows server)
add "Execute Windows Batch Command" and add the below content to the text field there.
cd %WORKSPACE%
grunt server runAppsData || exit 0
I hope this would work for you. Please try and let me know.
Consider rating my answer.
#Vishal try to use grunt for doing the same. So that you can easily integrate the Jenkins job with grunt task details.
Just configure and register task with grunt.
Then use the grunt task to run in jenkins.
If you want i can provide more details.

electron-windows-installer slow execution

I'm doing some deployment tests in windows and I'm using "electron-windows-installer" package to create a windows installer from my electron app.
I did it as a gulp task.
'use strict';
var gulp = require('gulp');
var winInstaller = require('electron-windows-installer');
gulp.task('create-windows-installer', function(done) {
winInstaller({
appDirectory: 'build/myApp',
outputDirectory: 'build/release',
iconUrl: 'URIToIcon',
exe: 'myApp.exe',
title: 'myApp',
setupExe: 'myApp.exe',
setpMsi: 'myApp.msi',
setupIcon: 'pathToIcon',
loadingGif: 'pathToGif',
arch: 'ia32'
}).then(done).catch(done);
});
And my package.json has the following command to run it from npm
"installer": "gulp windows-installer"
When I do npm run installer everything is working but the execution to create this installer is about 1 hour and 10 minutes. I have 52 dependencies in my project and my final executable is about 200MB. I'm wondering if it's normal that this process takes so long or something is bad in my code.
Thank you very much.
The process take too long because of the cache of folders/files to new build.
Just clean the outputDirectory (either appDirectory if necessary) and then build again, you'll good to go.

Resources