How to use tsconfig-paths with pm2? - pm2

I'm trying to deploy my typescript project with pm2, but the argument seems not working correctly.
Here is ecosystem.config.yml:
apps:
- name: 'node-app'
script: './src/main.ts'
interpreter: './node_modules/.bin/ts-node'
# they dont't work correctly below.
interpreter_args: '-r tsconfig-paths/register'
# args: '-T -r tsconfig-paths/register ./src/index.ts',
# args: '-r ./node_modules/tsconfig-paths/register ./src/main.ts'
# interpreter_args: ['--require=tsconfig-paths/register']
# interpreter_args: '-P . -r ./node_modules/tsconfig-paths/register'
kill_timeout: 10000
instances: max
exec_mode: cluster
env:
NODE_ENV: development
When I run pm2 start ecosystem.config.yml and check the logs then:
0|node-app | Error: Cannot find module '~framework/common/frame-util'
0|node-app | at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
0|node-app | at Function.Module._load (internal/modules/cjs/loader.js:507:25)
0|node-app | at Module.require (internal/modules/cjs/loader.js:637:17)
0|node-app | at require (internal/modules/cjs/helpers.js:20:18)
0|node-app | at Object.<anonymous> (/Users/zhaolin/__CODES__/__PERSONAL__/charley-nest-starter/script/ci/src/solution/gateway/auth/auth.service.ts:5:1)
0|node-app | at Module._compile (internal/modules/cjs/loader.js:689:30)
0|node-app | at Module.m._compile (/Users/zhaolin/.nvm/versions/node/v10.9.0/lib/node_modules/pm2/node_modules/ts-node/src/index.ts:473:23)
0|node-app | at Module._extensions..js (internal/modules/cjs/loader.js:700:10)
0|node-app | at Object.require.extensions.(anonymous function) [as .ts] (/Users/zhaolin/.nvm/versions/node/v10.9.0/lib/node_modules/pm2/node_modules/ts-node/src/index.ts:476:12)
0|node-app | at Module.load (internal/modules/cjs/loader.js:599:32)
And my tsconfig.json is:
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"rootDir": ".",
"paths": {
"~framework/*":["src/framework/*"],
"~solution/*":["src/solution/*"],
"~business/*":["src/solution/business/*"],
"~dto/*":["src/solution/dto/*"],
"~entities/*":["src/solution/entities/*"],
"~/*":["src/*"]
}
},
"exclude": ["node_modules", "dist"]
}
It seems that the paths alias are not working properly.
It works well without pm2(this is a nestjs project):
...
"start": "rimraf dist && cross-env NODE_ENV=development ts-node -r tsconfig-paths/register src/main.ts",
...
Can anyone help me with this problem?
Thanks.

Just like Aleksandr said you can first build the project using tsc and then run it using node, instead of ts-node.
Example:
In your script runner (within package.json) you can define:
"build": "tsc",
"runBuild": "pm2 start ecosystem.yml --only node-app"
In your ecosystem.yml you can define:
apps:
- name: 'node-app'
script: './dist/src/main.js'
node_args: '-r ts-node/register -r tsconfig-paths/register'
kill_timeout: 10000
instances: max
exec_mode: cluster
env:
NODE_ENV: development
To run:
$ npm run build
$ npm run runBuild
Hope that helps

In my case, I did resolve PM2 use with TS like the bellow
PM2 config file in the root folder: pm2.config.ts
// TS Setup
module.exports = {
apps: [
{
name: 'AppName',
script: './app/index.ts',
},
],
};
// JS setup
// module.exports = {
// apps: [
// {
// name: 'AppName',
// script: './dist/app/index.js',
// },
// ],
// };
Here is my package.json scripts section
"scripts": {
"compile": "tsc",
"test:ci": "jest",
"clean": "rimraf ./dist",
"test": "jest --watchAll --no-cache",
"ts:dev": "ts-node-dev --poll app/index.ts",
"start": "pm2 start --interpreter ts-node-dev pm2.config.ts",
"pm2:stop": "pm2 stop --interpreter ts-node-dev pm2.config.ts",
"js:dev": "npm run clean && npm run compile && node ./dist/app/index.js"
},

Related

How do I get webdriverIO to use a specified chromedriver

I need my webdriver tests use a specified chromedriver in a directory.
The problem is that when I run the tests it always uses a different chromedriver exe that was set as a default.
Command: "wdio run wdio.ci.conf.ts"
I get : "chromedriver: Starting ChromeDriver 97.0.4692.71"
ChromeDriver 97 is found in \node_modules\chromedriver\lib\chromedriver\chromedriver.exe
However in the wdio.ci.conf.ts file I set it to
services:[ ['chromedriver',{
chromeDriverCustomPath:"src\\main\\cucumber-webdriver-io\\node_modules\\webdriver-manager\\selenium\\chromedriver.exe"
}]],
At this location Im expecting it to pick an older version of chrome driver, 95.0.4638.69
I need it to run an older version as the corporate Jenkins environment has upgraded Chrome yet. In Jenkins I get the error:
WARN webdriver: Request failed with status 500 due to session not created: This version of ChromeDriver only supports Chrome version 97
[INFO] [0-0] Current browser version is 95.0.4638.69 with binary path /usr/bin/google-chrome
Thanks for your help
wdio.ci.conf.ts (removed the comments to be more brief)
const report = require('multiple-cucumber-html-reporter');
export const config: WebdriverIO.Config = {
autoCompileOpts: {
autoCompile: true,
tsNodeOpts: {
transpileOnly: true,
project: 'tsconfig.json'
}
}
},
specs: [
'./features/**/*.feature'
],
exclude: [
// 'path/to/excluded/files'
],
maxInstances: 10,
capabilities: [{
maxInstances: 5,
//
browserName: 'chrome',
'goog:chromeOptions':{
args: [ '--disable-dev-shm-usage', '--headless', '--no-sandbox', '--ignore-certificate-errors', '--test-type','--auth-server-whitelist=*bp.com', '--window-size=1440,1024', '--start-maximized']
},
acceptInsecureCerts: true,
}],
logLevel: 'info',
bail: 0,
baseUrl: 'http://localhost',
waitforTimeout: 10000,
connectionRetryTimeout: 120000,
connectionRetryCount: 3,
services:[ ['chromedriver',{
chromeDriverCustomPath:"src\\main\\cucumber-webdriver-io\\node_modules\\webdriver-manager\\selenium\\chromedriver.exe"
}]],
framework: 'cucumber',
reporters: ['cucumberjs-json'],
cucumberOpts: {
// <string[]> (file/dir) require files before executing features
require: ['./features/step-definitions/*-steps.ts'],
// <boolean> show full backtrace for errors
backtrace: false,
// <string[]> ("extension:module") require files with the given EXTENSION after requiring MODULE (repeatable)
requireModule: [],
// <boolean> invoke formatters without executing steps
dryRun: false,
// <boolean> abort the run on first failure
failFast: false,
// <boolean> hide step definition snippets for pending steps
snippets: true,
// <boolean> hide source uris
source: true,
// <boolean> fail if there are any undefined or pending steps
strict: false,
// <string> (expression) only execute the features or scenarios with tags matching the expression
tagExpression: '',
// <number> timeout for step definitions
timeout: 60000,
// <boolean> Enable this config to treat undefined definitions as warnings.
ignoreUndefinedDefinitions: false
},
onComplete: function(exitCode, config, capabilities, results) {
report.generate({
jsonDir: '.tmp/json/',
reportPath: '.tmp/report/'
});
},
}
package.json
{
"name": "cucumber-webdriver-io",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"wdio": "wdio run wdio.conf.ts",
"wdio-ci": "wdio run wdio.ci.conf.ts",
"postinstall": "rimraf -rm node_modules/wdio-html-nice-reporter/node_modules/#wdio/types"
},
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"cucumber": "^7.0.0-rc.0",
"expect-webdriverio": "^3.1.4",
"multiple-cucumber-html-reporter": "^1.18.3"
},
"devDependencies": {
"#types/chai": "^4.3.0",
"#types/node": "^17.0.12",
"#types/webdriverio": "^5.0.0",
"#wdio/cli": "^7.16.13",
"#wdio/cucumber-framework": "^7.16.13",
"#wdio/local-runner": "^7.16.13",
"#wdio/spec-reporter": "^7.16.13",
"#wdio/types": "^7.16.13",
"chai": "^4.3.6",
"chromedriver": "^97.0.2",
"cucumber-html-reporter": "^5.5.0",
"fs-extra": "^10.0.0",
"ts-node": "^10.4.0",
"typescript": "^4.5.5",
"wdio-chromedriver-service": "^7.2.6",
"wdio-cucumberjs-json-reporter": "^4.2.0",
"webdriver-manager": "^12.1.8",
"webdriverio": "^7.16.13"
}
}
Missed spelled
chromeDriverCustomPath >> chromedriverCustomPath

npm run build > not creating dist folder in NestJs project

I tried to start my project with npm run start:prod command but got
Error: Cannot find module {path to my project}\dist\main.js'.
I have tried to rename the path to all my files in the project from src/myController to ../myController .
My package.json (scripts)
"scripts": {
"build": "tsc -p tsconfig.build.json",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "ts-node -r tsconfig-paths/register src/main.ts",
"start:dev": "concurrently \"wait-on dist/main.js && nodemon\" \"tsc -w -p tsconfig.json\" ",
"start:debug": "nodemon --config nodemon-debug.json",
"prestart:prod": "rimraf dist && npm run build",
"start:prod": "node dist/main.js"
My tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"noImplicitAny": false,
"removeComments": true,
"allowSyntheticDefaultImports": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": true,
"rootDir": ".",
"outDir": "../dist",
"baseUrl": "./src"
},
"include": [ "./src/**/*.ts", ],
"exclude": ["node_modules", "dist", "src/**/*.spec.ts", "src/**/__test__/*"]
}
The actual output:
nest-typescript-starter#1.0.0 prestart:prod
{path to my project}
rimraf dist && npm run build
nest-typescript-starter#1.0.0 build
{path to my project}
tsc -p tsconfig.build.json
nest-typescript-starter#1.0.0 start:prod
{path to my project}
node dist/main.js
internal/modules/cjs/loader.js:584
throw err;
^
Error: Cannot find module
{path to my project}\dist\main.js'
Okeey, I was a little dumb. The answer is very easy. In package.json you need change line from "start:prod": "node dist/main.js" to "start:prod": "node dist/src/main.js". In tsconfig.json you need change "outDir": "../dist" to "outDir": "./dist"
you can just add a new command:
under the scripts in package.json :
"start:live": "rimraf dist && nest build && node dist/src/main",
then you can run:
npm run start:live

Error in deploy Cloud Functions .json not found

I can not deploy my functions when I try to import a .json credential file.
When running firebase init functions I selected the TypeScript
option.
Then I put my functions in TypeScript and tried loading the .json
file with the credentials of my project in order to use
firebase-admin.
/functions (Directory)
tsconfig.json
{
"compilerOptions": {
"lib": ["es6"],
"module": "commonjs",
"noImplicitReturns": true,
"outDir": "lib",
"sourceMap": true,
"target": "es6",
"types" : [ "node" ],
"esModuleInterop": true,
"resolveJsonModule": true,
},
"compileOnSave": true,
"include": [
"src",
"./typings.d.ts"
]
}
typings.d.ts:
declare module "*.json" {
const value: any;
export default value;
}
package.json:
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase serve --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"main": "lib/index.js",
"dependencies": {
"firebase-admin": "~6.0.0",
"firebase-functions": "^2.0.3"
},
"devDependencies": {
"tslint": "~5.8.0",
"typescript": "~2.8.3"
},
"private": true
}
functions/src/
-- serviceAccountKey.json
-- index.ts
index.ts:
import * as admin from 'firebase-admin';
import * as serviceAccount from './serviceAccountKey.json';
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "DATABASE-URL"
});
If I remove the import works normally, I can not deploy when I import the file.
Error:
i deploying functions
Running command: npm --prefix "functions" run lint
> functions# lint Z:\functions
> tslint --project tsconfig.json
Running command: npm --prefix "functions" run build
> functions# build Z:\functions
> tsc
tsconfig.json(11,5): error TS5023: Unknown compiler option 'resolveJsonModule'.
+ functions: Finished running predeploy script.
i functions: ensuring necessary APIs are enabled...
+ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
Error: Error parsing triggers: Cannot find module './serviceAccountKey.json'
Try running "npm install" in your functions directory before deploying.
You should use require() (not import) to pull in the contents of a JSON file. If you really must use import (I don't recommend it), read this.
If I remove the import works normally, I can not deploy when I import the file.
A few tsconfig options are missing:
"esModuleInterop": true,
"resolveJsonModule": true,

How to run webpack in production in a package.json script in windows with other commands?

I am using MERN stack and running windows 10. I am trying to run this npm run command from the package.json file.
"scripts": {
"build": "set NODE_ENV=production webpack && gulp",
"postinstall": "npm run build",
"start": "node ./bin/www"
},
When I run npm run build I get the following results:
terminal results
What happens is it looks like gulp runs and that is it. My bundle is not optimized for production at all. I will include the webpack file incase it is needed.
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: {
app: './src/app.js'
},
output: {
filename: 'public/build/bundle.js',
sourceMapFilename: 'public/build/bundle.map'
},
devtool: '#source-map',
plugins:
process.env.NODE_ENV === 'production'
? [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compress: {
warning: true
}
})
]
: [],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}
]
}
};
You might want to use cross-env, a platform-independent way to use environment variables:
"scripts": {
"build": "cross-env NODE_ENV=production webpack && gulp",
// or if the former does not work
"build": "npm run build:webpack && gulp",
"build:webpack": "cross-env NODE_ENV=production webpack",
},
Note that there are other ways to do production builds or evaluate environment variables in the webpack configuration.

sample path mismatching in AOT sample

I am trying to create Angular 2 sample ngc and JIT compiler. With JIT compiler i can run the sample but with ngc compiler am facing issue with component.html file path.
npm run ngc
ejangular2-systemjs-starter#1.0.0 ngc E:\AOT\seed-application-changes\sample-AOT
"node" copy-dist-files.js && rollup -c rollup-config.js && ngc -p tsconfig-aot.json
Error: Compilation failed. Resource file not found: E:/AOT/seed-application-changes/sample-AOT/src/src/app.
component.html
at ModuleResolutionHostAdapter.readResource (E:\AOT\seed-application-changes\sample-AOT\node_modules\#a
ngular\compiler-cli\src\compiler_host.js:291:19)
at CompilerHost.loadResource (E:\AOT\seed-application-changes\sample-AOT\node_modules\#angular\compiler
-cli\src\compiler_host.js:230:85)
at Object.get (E:\AOT\seed-application-changes\sample-AOT\node_modules\#angular\compiler\bundles\compil
er.umd.js:26365:111)
at DirectiveNormalizer._fetch (E:\AOT\seed-application-changes\sample-AOT\node_modules\#angular\compile
r\bundles\compiler.umd.js:13744:47)
at DirectiveNormalizer.normalizeTemplateAsync (E:\AOT\seed-application-changes\sample-AOT\node_modules\
#angular\compiler\bundles\compiler.umd.js:13790:25)
Below are my configuration.
sample structure
rollup.config.js
import nodeResolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify'
export default {
entry: 'src/main.js',
dest: 'aot/build.js', // output a single application bundle
sourceMap: false,
format: 'iife',
onwarn: function(warning) {
// Skip certain warnings
// should intercept ... but doesn't in some rollup versions
if ( warning.code === 'THIS_IS_UNDEFINED' ) { return; }
// intercepts in some rollup versions
if ( warning.indexOf("The 'this' keyword is equivalent to 'undefined'") > -1 ) { return; }
// console.warn everything else
console.warn( warning.message );
},
plugins: [
nodeResolve({jsnext: true, module: true}),
commonjs({
include: 'node_modules/rxjs/**',
}),
uglify()
]
}
tsconfig-aot.json
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
},
"files": [
"src/app.module.ts",
"src/main-aot.ts"
],
"angularCompilerOptions": {
"genDir": "aot",
"skipMetadataEmit" : true
}
}
package.json
"scripts": {
"start": "concurrently \"npm run tsc:w\" \"npm run lite\" ",
"lite": "lite-server",
"tsc": "tsc",
"tsc:w": "tsc -w",
"ngc": "\"node\" copy-dist-files.js && rollup -c rollup-config.js && ngc -p tsconfig-aot.json",
"serve": "lite-server -c bs-config.aot.json"
},