NestJS Application won't hot reload after using dotenv package - javascript

I try to configure hot reload on my Nestjs application using this article: https://docs.nestjs.com/recipes/hot-reload
I followed exactly the instructions in the first section ("With CLI") but it fails for me. But I do know the reason, just don't know how to resolve this issue. My hot reload script in package.json is exactly as the article says, except 1 change:
"start:dev": "dotenv -e ./envs/.env.development -e ../../prisma/.env.development nest build --watch",
This is my script. As you can see, I apply the process with some environment variables. When running in this way, application boots fine, but Hot Reload won't work. When booting only with "start:dev": "nest build --watch",
It runs with Hot Reload. (Note that I configure webpack in nest-cli.json file, this is why it missing in script statement).
Anyone could tell why applying my own envs makes this issue?
webpack.config.js file:
const nodeExternals = require('webpack-node-externals');
const { RunScriptWebpackPlugin } = require('run-script-webpack-plugin');
const configuration = (options, webpack) => ({
...options,
entry: ['webpack/hot/poll?100', options.entry],
externals: [
nodeExternals({
allowlist: ['webpack/hot/poll?100'],
}),
],
plugins: [
...options.plugins,
new webpack.HotModuleReplacementPlugin(),
new webpack.WatchIgnorePlugin({
paths: [/\.js$/, /\.d\.ts$/],
}),
new RunScriptWebpackPlugin({ name: options.output.filename, autoRestart: false }),
],
});
module.exports = configuration;
nest-cli.json file:
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "#nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"webpack": true,
"webpackConfigPath": "./webpack.config.js",
"deleteOutDir": true
}
}
main.ts file:
declare const module: any;
async function bootstrap() {
const prisma = new PrismaClient();
// * https://github.com/prisma/prisma/issues/5430#issuecomment-1098715558
await prisma.$runCommandRaw({
createIndexes: 'RefreshToken',
indexes: [
{
key: {
createdAt: 1,
},
name: 'Refresh Token Index',
expireAfterSeconds: JWT_REFRESH_TOKEN_DURATION_MINUTES * 60,
},
],
});
const app = await NestFactory.create(AppModule);
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => app.close());
}
const port = config.get('port', { infer: true });
await app.listen(port);
}
bootstrap();
Ny env file:
NODE_ENV="development"
PORT="3000"

Related

im trying to bundle my web app with webpack in my express js app

im trying to build my express app with webpack and i got a lot of errors i tried a lot of configs but nothing works , im using nodejs with express and ejs templating this is my first time using it to create something , i need to build it so i can deploy it , but i couldnt with all these errors:
const express = require("express");
var minify = require("express-minify");
const MainRoute = require("./routes/index");
const driver = require("./routes/driver");
const session = require("express-session");
const MySQLStore = require("express-mysql-session")(session);
const mysql = require("mysql2");
const crypto = require("crypto");
const bcrypt = require("bcrypt");
const multer = require("multer");
const path = require("path");
const Chart = require('chart.js/auto');
const Canvas = require('canvas');
const ejs = require('ejs');
const fs = require('fs');
// define the include function
ejs.filters.include = function(file, data) {
const filePath = path.join(__dirname, file);
const fileContent = fs.readFileSync(filePath, 'utf8');
return ejs.render(fileContent, data);
};
const app = express();
app.use(
minify({
cache: false,
uglifyJsModule: null,
errorHandler: null,
jsMatch: /javascript/,
cssMatch: /css/,
jsonMatch: /json/,
sassMatch: /scss/,
lessMatch: /less/,
stylusMatch: /stylus/,
coffeeScriptMatch: /coffeescript/,
})
);
app.use("/uploads", express.static(path.join(__dirname, "uploads")));
//------ Routes -------//
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use("/", MainRoute);
app.use("/", driver);
// rest of the code
//---------- Server is on ---------//
app.listen(1000, () => {
console.log("Server is On!!");
});
and my webpack.config.js :
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'production',
resolve: {
fallback: {
path: require.resolve("path-browserify"),
fs: false,
tls:false,
net:"empty",
"less": require.resolve("less"),
"vm": require.resolve("vm-browserify"),
"vm": false ,
https: require.resolve('https-browserify'),
crypto: require.resolve("crypto-browserify"),
stream: require.resolve("stream-browserify"),
zlib: require.resolve("browserify-zlib"),
assert: require.resolve("assert/"),
buffer: require.resolve("buffer/"),
process: require.resolve("process/browser"),
url: require.resolve("url/"),
os: require.resolve("os-browserify/browser"),
"timers": require.resolve("timers-browserify"),
"http": require.resolve("stream-http"),
"constants": require.resolve("constants-browserify"),
},
},
entry: {
server: './server.js'
},
output: {
path: path.resolve(__dirname, 'public'),
filename: '[name].js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-stage-2']
}
}
},
{
test: /\.ejs$/,
loader: 'ejs-loader',
options: {
esModule: false
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './views/index.ejs',
hash: true,
})
],
node: {
__dirname: false
},
target: 'node'
};
im new to nodejs i hope you guys would help me!
i tried to change the webpack configs and install all the dependencies
ERROR in ./server.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: [BABEL] C:\Users\anasa\Desktop\ADROAD\server.js:
As of v7.0.0-beta.55, we've removed Babel's Stage presets.
Please consider reading our blog post on this decision at
https://babeljs.io/blog/2018/07/27/removing-babels-stage-presets
for more details. TL;DR is that it's more beneficial in the
long run to explicitly add which proposals to use.
For a more automatic migration, we have updated babel-upgrade,
https://github.com/babel/babel-upgrade to do this for you with
"npx babel-upgrade".
If you want the same configuration as before:
{
"plugins": [
// Stage 2
["#babel/plugin-proposal-decorators", { "legacy": true }],
"#babel/plugin-proposal-function-sent",
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-proposal-numeric-separator",
"#babel/plugin-proposal-throw-expressions",
// Stage 3
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-syntax-import-meta",
["#babel/plugin-proposal-class-properties", { "loose": false }],
"#babel/plugin-proposal-json-strings"
]
}
If you're using the same configuration across many separate projects,
keep in mind that you can also create your own custom presets with
whichever plugins and presets you're looking to use.
module.exports = function() {
return {
plugins: [
require("#babel/plugin-syntax-dynamic-import"),
[require("#babel/plugin-proposal-decorators"), { "legacy": true }],
[require("#babel/plugin-proposal-class-properties"), { "loose": false }],
],
presets: [
// ...
],
};
};
(While processing: "C:\\Users\\anasa\\Desktop\\ADROAD\\node_modules\\#babel\\preset-stage-2\\lib\\index.js")
ERROR in Template execution failed: ReferenceError: _ is not defined
ERROR in ReferenceError: _ is not defined
- index.ejs:10 module.exports
C:/Users/anasa/Desktop/ADROAD/views/index.ejs:10:26
- index.js:450
[ADROAD]/[html-webpack-plugin]/index.js:450:16
- task_queues:95 process.processTicksAndRejections
node:internal/process/task_queues:95:5
- async Promise.all
webpack 5.75.0 compiled with 3 errors in 1650 ms
Probably you're using a deprecated stage preset.
Try to fix it with this:
1 - Install the right preset:
npm install --save-dev #babel/preset-env
2 - If you have a babel config file like .babelrc or babel.config.js make it use this preset instead, or update your webpack plugin instead:
{
"presets": [
["#babel/preset-env", {
"targets": {
"node": "current"
}
}]
]
}
3 - Remove the stage-0 and stage-1 presets from your Babel configuration.
Hope that help!

Django Vue3 project js not found

we are making a project using django and vue3. In this project, when I run the project with django while the project is running in vue3, django cannot see the App.js and chunk.js files. How can I solve this problem?
vue.config.js
const { defineConfig } = require('#vue/cli-service')
const BundleTracker = require('webpack-bundle-tracker')
module.exports = defineConfig({
transpileDependencies: true,
configureWebpack: {
plugins: [
new BundleTracker({ path: __dirname, filename: 'webpack-stats.json' }),
],
},
})
django settings.py
WEBPACK_LOADER = {
'DEFAULT': {
'CACHE': not DEBUG,
'STATS_FILE': str(BASE_DIR.joinpath('frontend', 'webpack-stats.json')),
'POLL_INTERVAL': 0.1,
'IGNORE': [r'.+\.hot-update.js', r'.+\.map'],
}
}

Entities loading for a Nx.dev Monorepo with Nest.js and TypeOrm

What I have been trying to do is to generate and run migrations with typeorm in the nest.js app within Nx.dev Monorepo.
But cannot find a way to do so.
My mono-repo looks like this
mono-repo structure
My database configurations look like this
database configurations
And this is how I have initialized my connection in the app.module.ts file
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useClass: DatabaseConfig
}),
I just wanted to know the way to generate and up the migrations.
Thanks and regards
In order to run typeorm cli in my Nx monorepo, I have added following target in my project.json:
"typeorm": {
"executor": "nx:run-commands",
"outputs": [],
"options": {
"command": "TS_NODE_PROJECT=apps/web-api/tsconfig.app.json ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli --config ./apps/web-api/src/database/cli.ts",
"cwd": "."
}
},
where cli.ts returns DataSourceOptions in my command line configuration.
Inside I have following configuration for migrations options:
migrations: [path.join(__dirname, 'migrations', '*.[tj]s')],
cli: {
migrationsDir: path.join(__dirname, 'migrations')
},
I execute it with following package.json script:
"migration:generate:web-api": "nx typeorm --project=web-api -- migration:generate -n",
In order to run migrations, I have added webpack configuration:
const glob = require('glob');
module.exports = (config, context) => {
if (config.mode === 'production') {
config.optimization = {
minimize: false,
};
const sourcePaths = ['apps/web-api/src/database/migrations/**/*.[tj]s'];
const additionalEntries = sourcePaths
.flatMap((entryPath) => glob.sync(entryPath, { absolute: false }))
.reduce((previous, current) => {
const filename = current.split('src/')[1];
previous[filename] = current;
return previous;
}, {});
config.entry = {
...config.entry,
...additionalEntries,
};
}
return config;
};
and configured my build target to use it with:
"build": {
...
"options": {
...
"webpackConfig": "apps/web-api/webpack.config.js",
}
}

Webpack watch is failing me

EDIT: It's now resolved. Got in to work this morning and thought "have you tried turning it on and off again?". So I did. Removed node_modules, reinstalled all packages - it worked. FML.
I'm upgrading to Webpack 4 and can't seem to get the watch to work.
When I run the watch script everything runs as expected the first time, but errors out during a file update.
The scripts I try:
"dev": "cross-env ENV=dev webpack --config config/bundling/webpack.config.js --mode=development",
"watch": "cross-env WATCH=true yarn run dev --watch"
(redundancies in the cross-env variables will be fixed later)
The errors I get are the following:
"WARNING in configuration
The 'mode' option has not been set, webpack will fallback to
'production' for this value. Set 'mode' option to 'development' or
'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior.
Learn more: https://webpack.js.org/concepts/mode/"
"ERROR in multi (webpack)-dev-server/client?http://localhost:8080 ./src
Module not found: Error: Can't resolve './src' in [MY PATH HERE]
# multi (webpack)-dev-server/client?http://localhost:8080 ./src main[1]"
It seems like it doesn't read my webpack.config.js or the mode variable the on watch? Also, it succeeds in building the bundle, leading me to thing this might be an issue solely with the built-in webpack-dev-server.
I've tried everything I can think of, changing the scripts, changing the syntax of the mode flag, setting mode in webpack.config.js, tried relative paths, tried absolute paths, tried different versions of webpack and webpack-dev-server, moved my config file to the project root, sacrificed a small CPU to the Gods of code - nothing works.
I've been at this for days without any progress. Any help would be appreciated.
Versions:
"webpack": "^4.27.1",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.10"
Config:
require('dotenv').config()
const CopyWebpackPlugin = require('copy-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const BrowserSyncPlugin = require('browser-sync-webpack-plugin')
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
const moduleRules = require('./module.rules')
const config = require('./editable.config')
module.exports = function() {
const isDev = !!(process.env.ENV === 'dev')
const isProd = !!(process.env.ENV === 'prod')
const doServe = !!(process.env.SERVE === 'true')
const doWatch = !!(process.env.WATCH === 'true')
const webpackConfig = {
// Set mode
mode: isProd ? 'production' : 'development',
// Entry points.
entry: config.entrypoints,
// JS output name and destination.
output: {
path: config.paths.public,
filename: config.outputs.javascript.filename
},
// External dependencies.
externals: config.externals,
// Custom resolutions.
resolve: config.resolve,
// Rules for handling filetypes.
module: {
rules: [
moduleRules.javascript,
moduleRules.sass,
moduleRules.fonts,
moduleRules.images,
]
},
// Plugins running in every build.
plugins: [
new FriendlyErrorsWebpackPlugin(),
new MiniCssExtractPlugin(config.outputs.css),
new CleanWebpackPlugin(config.paths.public, { root: config.paths.root }),
new CopyWebpackPlugin([{
context: config.paths.images,
from: {
glob: `${config.paths.images}/**/*`,
flatten: false,
dot: false
},
to: config.outputs.image.filename,
}]),
new CopyWebpackPlugin([{
context: config.paths.fonts,
from: {
glob: `${config.paths.fonts}/**/*`,
flatten: false,
dot: false
},
to: config.outputs.font.filename,
}]),
],
devtool: isDev ? config.settings.sourceMaps : false,
watch: doWatch
}
// Set BrowserSync settings if serving
if (doServe) {
// setting our default settings...
const browserSyncSettings = {
host: 'localhost',
port: 3000,
proxy: process.env.HOME,
files: [
{
match: ['../../**/*.php'],
fn: function (event, file) {
if (event === 'change') {
this.reload()
}
}
}
]
}
// ...and overwriting them with user settings
Object.assign(browserSyncSettings, config.settings.browserSync)
webpackConfig.plugins.push(new BrowserSyncPlugin(browserSyncSettings))
}
return webpackConfig;
}
Config, part 2
const path = require('path')
module.exports = {
paths: {
root: path.resolve(__dirname, '../../'),
public: path.resolve(__dirname, '../../public'),
src: path.resolve(__dirname, '../../src'),
javascript: path.resolve(__dirname, '../../src/js'),
sass: path.resolve(__dirname, '../../src/sass'),
fonts: path.resolve(__dirname, '../../src/fonts'),
images: path.resolve(__dirname, '../../src/images'),
relative: '../../',
external: /node_modules/
},
entrypoints: {
main: ['./src/js/app.js', './src/sass/style.scss']
},
outputs: {
javascript: { filename: 'js/[name].js' },
css: { filename: 'css/[name].css' },
font: { filename: 'fonts/[path][name].[ext]' },
image: { filename: 'images/[path][name].[ext]' }
},
externals: {
},
resolve: {
},
settings: {
sourceMaps: 'cheap-module-source-map',
autoprefixer: {
browsers: ['last 3 versions', '> 1%', 'ie >= 10'],
},
browserSync: {
host: 'localhost',
port: 3000
}
}
}
Bonus question: is it possible to watch without having Webpack 4 start up a new devServer?
Thanks! <3

Configure Webpack with Electron to use ES6 imports?

I am trying to use Webpack since I want to use ES modules in my Electron application but having some hurdles. I just want to use import in my main as well as renderer processes.
My application structure is as follows -
- src/ // contains basic html, css & js
- index.html // <h1>Hello World</h1>
- style.css // is empty
- app.js // console.log('it works 🙈')
- app/ // contains electron code
- main_window.js
- custom_tray.js
- index.js // entry point for electron application
- dist/ // output bundle generated from webpack
- bundle.js
My index.js file looks like -
import path from "path";
import { app } from "electron";
import MainWindow from "./app/main_window";
import CustomTray from "./app/custom_tray";
let win = null,
tray = null;
app.on("ready", () => {
// app.dock.hide();
win = new MainWindow(path.join("file://", __dirname, "/src/index.html"));
win.on("closed", () => {
win = null;
});
tray = new CustomTray(win);
});
My main_window.js file looks like -
import { BrowserWindow } from "electron";
const config = {
width: 250,
height: 350,
show: false,
frame: false,
radii: [500, 500, 500, 500],
resizable: false,
fullscreenable: false
};
class MainWindow extends BrowserWindow {
constructor(url) {
super(config);
this.loadURL(url);
this.on("blur", this.onBlur);
this.show();
}
onBlur = () => {
this.hide();
};
}
export default MainWindow;
My custom_tray.js looks like -
import path from "path";
import { app, Tray, Menu } from "electron";
const iconPath = path.join(__dirname, "../src/assets/iconTemplate.png");
class CustomTray extends Tray {
constructor(mainWindow) {
super(iconPath);
this.mainWindow = mainWindow;
this.setToolTip("Thirsty");
this.on("click", this.onClick);
this.on("right-click", this.onRightClick);
}
onClick = (event, bounds) => {
const { x, y } = bounds;
const { width, height } = this.mainWindow.getBounds();
const isMac = process.platform === "darwin";
if (this.mainWindow.isVisible()) {
this.mainWindow.hide();
} else {
this.mainWindow.setBounds({
x: x - width / 2,
y: isMac ? y : y - height,
width,
height
});
this.mainWindow.show();
}
};
onRightClick = () => {
const menuConfig = Menu.buildFromTemplate([
{
label: "Quit",
click: () => app.quit()
}
]);
this.popUpContextMenu(menuConfig);
};
}
export default CustomTray;
And my webpack.main.config.js looks like -
const path = require("path");
const config = {
entry: "./index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js"
},
module: {
rules: [{ test: /\.js$/, exclude: /node_modules/, use: "babel-loader" }]
},
stats: {
colors: true
},
target: "electron-main",
devtool: "source-map"
};
module.exports = config;
And my webpack.renderer.config.js looks like -
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const config = {
entry: "./src/app.js",
output: {
path: path.resolve(__dirname, "dist/renderer"),
filename: "app.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: "babel-loader"
},
{
test: /\.css$/,
use: {
loader: "css-loader",
options: {
minimize: true
}
}
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
use: {
loader: "url-loader",
query: {
limit: 10000,
name: "imgs/[name].[ext]"
}
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
use: {
loader: "url-loader",
query: {
limit: 10000,
name: "fonts/[name].[ext]"
}
}
}
]
},
stats: {
colors: true
},
target: "electron-renderer",
devtool: "source-map",
plugins: [
new CopyWebpackPlugin([
{ from: "src/app.css" },
{ from: "src/assets", to: "assets/" }
]),
new HtmlWebpackPlugin({
filename: "index.html",
template: path.resolve(__dirname, "./src/index.html"),
minify: {
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true
}
})
]
};
module.exports = config;
My scripts in package.json look like
"scripts": {
"dev:main": "webpack --mode development --config webpack.main.config.js",
"dev:renderer": "webpack --mode development --config webpack.renderer.config.js",
"dev:all": "npm run dev:main && npm run dev:renderer",
"build:main": "webpack --mode production --config webpack.main.config.js",
"build:renderer": "webpack --mode production --config webpack.renderer.config.js",
"build:all": "npm run build:main && npm run build:renderer",
"prestart": "npm run build:all",
"electron": "electron dist/index.js",
"start": "npm run electron",
}
Currently my application creates a dist/bundle.js but when I run electron dist/bundle.js it doesn't work. I get it, it might be because it does not contain src folder but when I copy src folder into dist it still doesn't work.
Firstly, I run npm run dev:main to generate dist/bundle.js then I run npm run dev:renderer to generate dist/renderer/bundle.js & then I run npm run start to start my electron application.
It gives me error "Uncaught Exception: Error: Requires constructor call at new MainWindow" which is in index.js where I call constructor new MainWindow()
I just want to use ES6 in all my JS files. Is there any boilerplate because the ones I found have tons of additional stuff like React JS & all plus a huge number of optimizations ?
After 8 days I found the answer finally. It works with ESM in Electron.
I've made a repo that is minimum & lets you write ESM with Electron.
The complete code can be found at https://github.com/deadcoder0904/electron-webpack-sample
Its very minimal so it should be easy to understand.

Categories

Resources