Using environment variables in nx based nodejs app - node.js

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.

Related

"The requested module does not provide an export named 'default'", but export is provided - Self build NPM package

I am writing my first NPM package as a plugin for Vite. I had all the code in my plugin before in a separate file inside the same code base, but now I have split and separated it into a it's own nuget package.
When I use the package in my sample projects and I run npm run dev I get this error which I didn't get before:
failed to load config from C:\Users\cjime\Desktop\Open Source Projects\Vite.NET\dotnet-vite\ClientApp\vite.config.ts
error when starting dev server:
file:///C:/Users/cjime/Desktop/Open%20Source%20Projects/Vite.NET/dotnet-vite/ClientApp/vite.config.ts.timestamp-1674663682047.mjs:4
import ViteDotNet from "file:///C:/Users/cjime/Desktop/Open%20Source%20Projects/Vite.NET/dotnet-vite/ClientApp/node_modules/vite-dotnet/lib/index.js";
^^^^^^^^^^
SyntaxError: The requested module 'file:///C:/Users/cjime/Desktop/Open%20Source%20Projects/Vite.NET/dotnet-vite/ClientApp/node_modules/vite-dotnet/lib/index.js' does not provide an export named 'default'
Which is strange because there is a default export. The following is the only code file used/exposed in the plugin, it's not a large codebase
import type { UserConfig } from 'vite';
import { basename, posix } from 'path';
export type PluginConfig = {
port: number;
appFolder: string;
entrypoint: string;
prodServerOrigin?: string; //Not for initial release. Use when hosting app files in a remote server such as S3 or Azure Blob.
}
function outputOptions (assetsDir: string) {
// Internal: Avoid nesting entrypoints unnecessarily.
const outputFileName = (ext: string) => ({ name }: { name: string }) => {
const shortName = basename(name).split('.')[0]
return posix.join(assetsDir, `${shortName}.[hash].${ext}`)
}
return {
entryFileNames: outputFileName('js'),
chunkFileNames: outputFileName('js'),
assetFileNames: outputFileName('[ext]'),
}
}
export default function ViteDotNetPlugin(entrypoint: string, port: number = 5173, appFolder: string = "ClientApp") {
return ViteDotNet({ port, appFolder: appFolder, entrypoint: entrypoint });
}
function ViteDotNet(config: PluginConfig) {
return {
name: 'ViteDotNet',
enforce: "post" as const,
config: (userConfig: UserConfig/*, { command, mode }*/) => {
//https://vitejs.dev/config/server-options.html#server-origin
return {
server: {
origin: `http://localhost:${config.port}`,
hmr: {
protocol: 'ws'
}
},
build: {
outDir: `../wwwroot`,
emptyOutDir: false,
manifest: `${config.appFolder}/manifest.json`,
rollupOptions: {
// overwrite default .html entry
input: config.entrypoint,
output: outputOptions(config.appFolder)
}
}
}
}
};
};
Now, I realize this might be because of an error on my part when configuring the package.json file. Here it is:
{
"name": "vite-dotnet",
"version": "0.2.8",
"description": "Integration plugin for ASP.NET Core and ViteJS",
"main": "lib/index.js",
"keywords": [
"vite",
"vite-integration",
"react",
"svelte",
"vue",
"solidjs",
"lit"
],
"repository": {
"type": "git",
"url": "git+https://github.com/techgems/Vite.NET"
},
"type": "module",
"files": ["lib/**/*"],
"types": "lib/index.d.ts",
"author": "TechGems",
"license": "MIT",
"scripts": {
"build": "tsc"
},
"devDependencies": {
"#types/node": "^18.11.18",
"tslib": "^2.4.0",
"typescript": "^4.6.4",
"vite": "^3.2.3"
}
}
Here is also a link to the entire codebase of the plugin:
https://github.com/techgems/Vite.NET/tree/master/ViteDotNet/Plugin
as well as the NPM package: https://www.npmjs.com/package/vite-dotnet
Thanks in advance and please let me know if you need more information.

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 vscode debugger with webpack and node.js

Currently I'm working on a backend application using express + node.js and webpack as the bundler.
So far, I was able to run and test my code without any problem.
I would like now to use the Visual Studio Code debugger in order to debug my application. I tried to follow along this tutorial https://medium.com/#jsilvax/debugging-webpack-with-vs-code-b14694db4f8e
Now, when I try to launch my debugger, it just prints to the console Webpack is watching the files… without actually run my server
Here is my launch.json file:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Webpack",
"program": "${workspaceFolder}/node_modules/webpack/bin/webpack.js",
"args": [
"--config", "./webpack.config.js"
],
}
]
}
And here is my webpack.config.js file:
const webpack = require('webpack')
const path = require('path')
const nodeExternals = require('webpack-node-externals')
const StartServerPlugin = require('start-server-webpack-plugin')
module.exports = {
entry: ['webpack/hot/poll?1000', './src/index'],
watch: true,
devtool: 'sourcemap',
target: 'node',
node: {
__filename: true,
__dirname: true
},
externals: [nodeExternals({ whitelist: ['webpack/hot/poll?1000'] })],
module: {
rules: [
{
test: /\.js?$/,
use: [
{
loader: 'babel-loader',
options: {
babelrc: false,
presets: [['env', { modules: false }], 'stage-0'],
plugins: ['transform-regenerator', 'transform-runtime']
}
}
],
exclude: /node_modules/
},
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
use: {
loader: 'raw-loader'
}
}
]
},
plugins: [
new StartServerPlugin('server.js'),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.DefinePlugin({
'process.env': { BUILD_TARGET: JSON.stringify('server') }
}),
new webpack.SourceMapDevToolPlugin({
filename: '[name].js.map'
}),
new webpack.BannerPlugin({ banner: 'require("source-map-support").install();', raw: true, entryOnly: false })
],
output: { path: path.join(__dirname, 'dist'), filename: 'server.js' }
};
Also, this is my project structure:
To run this application without using the debugger, I have a start script which looks like this:
"start": "webpack --colors --progress"
As I was saying, when I launch the debugger, it simply hangs and doesn't do anything. The only message I get inside the debugger console is Webpack is watching the files…
I'm think, that your configuration is not correct. In "program", choose file from your application, not from webpack, for example, "server.js" or as below, "index.js".
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/index.js"
}
There can be also other problem - do you have any breakpoints added in VSCode? If not, debugger just doesn't work.

auto-update files are deleted after auto-update

Hello everyone I build the installer with nsis ia32 arch, I use sqlite3 and everything works fine until the update is downloaded since it replaces all the files in the installation folder.
Then my database file is deleted, how can I prevent my database file from being deleted with the new versions?
Here I initialize my connection
export default class Connection {
private connection;
public initConnection(isTest) {
this.connection = new (sqlite3.verbose()).Database('filename.db');
}
.
.
.
}
Here my build config
"build": {
"win": {
"target": [{
"target": "nsis",
"arch": ["ia32"]
}],
"icon": "src/assets/images/icons/icon256.ico",
"publisherName": "spaces"
},
"publish": {
"provider": "spaces",
"name": "<space-name>",
"region": "nyc3"
}
}
electron-builder v19.33.0
electron-updater v2.10.1
thanks o/

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

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
}

Resources