how to prevent lite-server from opening browser window on startup? - node.js

I'm using the lite-server with npm run lite
my config file,
module.exports = {
"server": { "baseDir": "./src" }
};
whenever I start the server, it opens up a new browser window. How do I prevent lite server opening browser window on server startup?
thanks.

It seems like browserSync has option open: false
https://www.browsersync.io/docs/options/#option-open
try in your bs-config.js
module.exports = {
"server": { "baseDir": "./src" },
"open": false
};
Or in bs-config.json in your project's folder:
{
"server": { "baseDir": "./src" },
"open": false
}

Lite-server uses
BrowserSync
And allows for configuration overrides via a local
bs-config.json
or
bs-config.js
file in your project.
The default behavior of the server serves from the current folder, opens a browser, and applies an HTML5 route fallback to ./index.html. so we need to set the configuration
For example, to change the server port, watched file paths, and base directory for your project, create a bs-config.json in your project's folder:
{
"port": 8000,
"files": ["./src/**/*.{html,htm,css,js}"],
"server": { "baseDir": "./src" }
}
So for browser not opening you have to set like this
{
"port": 8000,
"files": ["./src/**/*.{html,htm,css,js}"],
"server": { "baseDir": "./src" },
"open":false
}

Related

Debugging Node.js with Typescript using Webpack in VSCode is impossible, please some advice

I expend almost 6 hours trying to make this work but it seems it refuses by all methods.
I made a simple API with NodeJS using Typescript and Webpack, but when I tried to debug it put break points and all of that stuff, VSCode put it very difficult.
Launch.json :
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"preLaunchTask": "npm: start - server",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\server\\webpack.config.ts",
"outFiles": [
"${workspaceFolder}/server/dist/index.js"
],
"sourceMaps": true,
"trace": true
}
]
}
webpack.config.ts :
const webpack = require("webpack");
const path = require("path");
const nodeExternals = require("webpack-node-externals");
module.exports = {
entry: ["./src/index.ts"],
devtool: "source-map",
watch: true,
target: "node",
externals: [
nodeExternals({
allowlist: ["webpack/hot/poll?100"]
})
],
module: {
rules: [
{
use: "ts-loader",
exclude: /node_modules/
}
]
},
mode: "development",
resolve: {
extensions: [".tsx", ".ts", ".js"]
},
plugins: [new webpack.HotModuleReplacementPlugin()],
output: {
path: path.join(__dirname, "dist"),
filename: "index.js"
}
};
index.ts of my app which uses middleware with routers to redirect url requests.
import express from "express";
import cors from "cors";
import helmet from "helmet";
import { categoryRouter } from "./routers/category.router";
import { CategoryPostgre } from "./database/postgre/category.postgre";
dotenv.config();
/**
* App Variables
*/
if (!process.env.PORT) {
process.exit(1);
}
const PORT: number = parseInt(process.env.PORT as string, 10);
const app = express();
const router = express.Router();
/**
* App Configuration
*/
app.use(helmet());
app.use(cors());
app.use(express.json());
/**
* Service Initialization
*/
console.log(`Inicializando Servicios`);
app.use('/api/category', categoryRouter);
/**
* Server Activation
*/
const server = app.listen(PORT, () => {
console.log(`----------------------------------------------------------------`);
console.log(`--- App V 0.1 NodeJS Server Listening on port ${PORT} ---`);
console.log(`----------------------------------------------------------------`);
tsconfig.json :
{
"compilerOptions": {
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"sourceMap": true, /* Generates corresponding '.map' file. */ /* Enable all strict type-checking options. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
}
}
I want just the debugger to stay listening to break points, so when I trigger a request using postman, it stops on my categoryRouter function and I can see what's going on right there.
Now it just do nothing when I run it.
As far as I know there are 2 types of request when configuring a launch.json :
launch: which will launch a new server on its own.
attach: which tells to vscode whenver you press the start debug button, to attach the debbuger to an existing running process.
The first option is mostly used for when you want to debbug a script in the sense of, it can run on its own and it does not expect external input.
Second one can be used if you have your server already running on whatever port you have specified.
Try the following:
package.json:
{
"scripts": {
"build": "webpack",
"start": "nodemon --inspect=0.0.0.0:9229 lib/index.js",
...
}
}
Note lib/index.js is my compiled file, as I'm using ts in my project.
--inspect=...:9229 tells the running server to listen for a client connection (debugger) on the specified port.
if your server is running inside docker leave the host address to: 0.0.0.0 but if you're not using it, set it to: 127.0.0.1
Then you need to configure your .vscode/launch.json so that it can connect to the server.
this is the config I'm using:
{
"version": "0.2.0",
"configurations": [
{
"name": "Docker: Attach to Node",
"type": "node",
"request": "attach",
"restart": true,
"port": 9229,
"address": "localhost",
"localRoot": "${workspaceFolder}",
"remoteRoot": "/application",
"protocol": "inspector"
}
]
}
Note /application is the WORKDIR I have defined in my Dockerfile
if you're not using docker, you probably don't need this property.
With this set up, I can have docker running my server, and at any point I need to debug an endpoint in my server, I can simply run the debugger from vscode, and add a breakpoint in my source code, then from postman when I trigger a request, vscode will pause the execution at the breaking point.
Good luck, hope this helps. :)

Using environment variables in nx based nodejs app

I've setup a project with several nodejs and angular apps inside a nrwl/nx workspace.
I'm trying to work with the environment files
inside the nodejs apps.
I've setup the import like this:
import {environment} from './environments/environment';
Then I ran ng serve my-node-app and it shows the environment for non production.
Now I tried to do ng serve my-node-app --prod to see how the app works with a production setup - but I get the error:
Configuration 'production' could not be found in project my-node-app.
Here's the project's angular.json config:
"ui-server": {
"root": "apps/ui/server",
"sourceRoot": "apps/ui/server/src",
"projectType": "application",
"prefix": "ui-server",
"schematics": {},
"architect": {
"build": {
"builder": "#nrwl/builders:node-build",
"options": {
"outputPath": "dist/apps/ui/server",
"main": "apps/ui/server/src/main.ts",
"tsConfig": "apps/ui/server/tsconfig.app.json",
"assets": ["apps/ui/server/src/assets"]
},
"configurations": {
"production": {
"optimization": true,
"extractLicenses": true,
"fileReplacements": [
{
"replace": "apps/ui/server/src/environments/environment.ts",
"with": "apps/ui/server/src/environments/environment.prod.ts"
}
]
}
}
},
"serve": {
"builder": "#nrwl/builders:node-execute",
"options": {
"buildTarget": "ui-server:build"
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"apps/ui/server/tsconfig.app.json",
"apps/ui/server/tsconfig.spec.json"
],
"exclude": ["**/node_modules/**"]
}
},
"test": {
"builder": "#nrwl/builders:jest",
"options": {
"jestConfig": "apps/ui/server/jest.config.js",
"tsConfig": "apps/ui/server/tsconfig.spec.json"
}
}
}
}
Am I missing something?
I've found this post when I was looking how to fetch the environmental variables defined in .env file.
process.env.ENVIRONMENTAL_VARIABLES in frontend part can be accessed when rendering on the server (e.g. Angular Universal), having .env in the root of Nrwl monorepo and webpack properties, such as:
const dotenv = require('dotenv-webpack');
module.exports = {
plugins: [
new dotenv(),
],
};
Don't forget to change your angular.json:
...
"architect": {
"build": {
"builder": "#angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./webpack.browser.config.js",
"replaceDuplicatePlugins": true
},
...
I've named the custom webpack as webpack.browser.config.js.
Now, let say you have a server/..., which you're using for some backend stuff, then you won't have them accessible there. You need to install dotenv package and in the server/main.ts, let say that's your server's root, require this package, that way:
require('dotenv').config();
Note: until Angular 8 we were able to set up also webpack-server related logic, in a file such as webpack.server.config.js. Therefore, it was doable to apply basically same code related to dotenv, which was in webpack.browser.config.js. However, it doesn't work anymore. Angular CLI Builders are being used to build & server SSR apps instead.
Deploying to Firebase/using Cloud Functions for Firebase (and possibly other Serverless/FaaS)?
Then in your functions folder you need to paste the .env file as well. I assume here that from functions you're deploying.
For debugging I'd advise:
console.log(require('dotenv').config({ debug: true }));
Might save you a lot of time.

electron-updater: Can not find module 'debug'

I am developing Desktop App(windows/mac) using Electronjs. I was trying to implement auto-update feature using electron-updater since I am using electron-builder for the building.
I am able to generate .exe file for my app but when trying to install, it's throwing an error: "Can not find module 'debug'". Please find attached screenshot.
Without electron-updater implementation, my app is running fine. When I am importing autoUpdator in my index.js, started getting that error. I am using autoUpdator as below:
const {autoUpdater} = require("electron-updater");
autoUpdater.on('update-downloaded', (ev, info) => {
setTimeout(function() {
autoUpdater.quitAndInstall();
}, 5000)
})
app.on('ready', ()=> {
autoUpdater.checkForUpdates();
});
Please find the libraries description below:
"electron-updater": "^4.0.6"
"electron": "^3.0.6"
"electron-builder": "^20.38.4"
I followed below links:
Electron builder Auto Update
electron builder using local server
I am new to the Electron js actively looking for your support.
As asked please find my build configuration below:
"build": {
"appId": "com.****.*****",
"productName": "********",
"directories": {
"output": "build"
},
"publish": [
{
"provider": "generic",
"url": "http://127.0.0.1:4080/"
}
],
"nsis": {
"oneClick": false,
"perMachine": true,
"allowElevation": true,
"allowToChangeInstallationDirectory": true,
"deleteAppDataOnUninstall": true,
"createDesktopShortcut": true
},
"win": {
"target": "nsis"
},
"files": [
"!**/.vscode",
"!**/build",
"!**/config",
"!**/assets/data",
"!**/src"
],
"extraResources": [
{
"from": "src/assets/data",
"to": "dist/assets/data",
"filter": "database*"
}
]
},
The line "!**/src" in your exclude list is the culprit.
Many node modules will have "src" folders which have to be packaged/bundled along with your application source code.
If you observe "debug" module folder under "node_modules" it has a "src" folder which has been excluded by above rule.
Suggestion: If you have your apps source folder as "src", rename it to something else like "source" (which is in your control), but ensure you don't exclude "src" folders of node_modules (renaming these is not in your control as it could break the module's integrity and they get overwritten on fresh npm install also)

Using Gulp nodemon with the VSCode inspector

I am trying to figure out the VSCode launch configuration for launching a gulp task in the inspect mode. The gulp task internally transpiles the code and runs the process via gulp-nodemon. Example is given as below:
VSCode Launch script:
{
"type": "node",
"request": "launch",
"name": "Gulp App debug",
"program": "${workspaceRoot}\\node_modules\\gulp\\bin\\gulp.js",
"args": [
"serve:dev"
],
"sourceMaps": true,
"outputCapture": "std"
}
Gulp Task:
gulp.task("serve:dev", ["release"], () => {
const through = require("through2");
const nodemon = require("gulp-nodemon");
const nodemonStream = nodemon({
script: "dist/src/app.js",
ext: "",
exec: 'node --inspect',
// nodeArgs: ['--inspect'],
watch: "none", // Disabled, will be triggered externally.
env: Object.assign(process.env, {
LOG_LEVEL: "debug",
EXEC_MODE: "dev",
NODE_PATH: "dist/src"
})
});
const watchSrc = watch("./src/**/*", vinyl => {
return compileSourcesStream(
gulp.src(vinyl.path),
gulp.dest("dist/src")
).pipe(
through.obj(function(chunk, enc, cb) {
nodemonStream.emit("restart");
cb(null, chunk);
})
);
});
In the above configuration, the VSCode launches the gulp task with the inspect mode binding to a random port. However the gulp task itself runs the nodemon with the inspect mode pointing to a different new random port. This leads to VSCode unable to track the launched process.
Any suggestion on the above setup ?

Browser-sync - serve "node_modules" out of "src" directory

I'm using browsersync via lite-server, and have the following configuration:
{
"port": 8000,
"files": [
"./src/**/*.{html,htm,css,js}"
],
"server": {
"baseDir": "./src",
"routes": {
"node_modules": "../node_modules" <--- Attempt to serve node_modules
}
}
}
Project layout is like this:
node_modules
src
|-app
|-index.html
|-systemjs.config.js
package.json
bs-config.json
The problem is that inside index.html any reference like
<script src="node_modules/....js"> fails with a 404.
How can I serve paths outside of .src directory?
You can expose whole project folder by adding one more element to baseDir as Edvin mentioned.
But it would be better if you will expose only /node_modules using routes:
module.exports = {
server : {
baseDir : './dist',
routes : {
'/vendor' : './node_modules'
}
}
}
You can use multiple directory in baseDir config:
{
"server": {
"baseDir": ["./", "./src" ]
}
}

Resources