How to import ipcRenderer in react? - javascript

I've tried to import ipcRenderer in react app
import {ipcRenderer} from 'electron';
but I get this error message : require is not defined

You'll want to follow the steps I outline in this comment. These steps ensure security in your electron app.
main.js
const {
app,
BrowserWindow,
ipcMain
} = require("electron");
const path = require("path");
const fs = require("fs");
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;
async function createWindow() {
// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false, // is default value after Electron v5
contextIsolation: true, // protect against prototype pollution
enableRemoteModule: false, // turn off remote
preload: path.join(__dirname, "preload.js") // use a preload script
}
});
// Load app
win.loadFile(path.join(__dirname, "dist/index.html"));
// rest of code..
}
app.on("ready", createWindow);
ipcMain.on("toMain", (event, args) => {
fs.readFile("path/to/file", (error, data) => {
// Do something with file contents
// Send result back to renderer process
win.webContents.send("fromMain", responseObj);
});
});
preload.js
const {
contextBridge,
ipcRenderer
} = require("electron");
// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
"api", {
send: (channel, data) => {
// whitelist channels
let validChannels = ["toMain"];
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
let validChannels = ["fromMain"];
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`
ipcRenderer.on(channel, (event, ...args) => fn(...args));
}
}
}
);
index.html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8"/>
<title>Title</title>
</head>
<body>
<script>
window.api.receive("fromMain", (data) => {
console.log(`Received ${data} from main process`);
});
window.api.send("toMain", "some data");
</script>
</body>
</html>

You need to use
const { ipcRenderer } = window.require("electron");
Otherwise it will try to import it from Webpack or whatever module bundler you use.
You can checkout this thread for a better explanation:
https://github.com/electron/electron/issues/7300

if you are looking to quickly try IPC in electron in a react component, this may help.
main.js
const {ipcMain} = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => {
console.log("heyyyy",arg) // prints "heyyyy ping"
})
App.js
import React from 'react';
import './App.css';
const { ipcRenderer } = window.require('electron');
function App() {
return (
<div className="App">
<button onClick={()=>{
ipcRenderer.send('asynchronous-message', 'ping')
}}>Com</button>
</div>
);
}
export default App;
Output:
Don't forget to re-run the app after making the changes.
No preload.js added, Did not change anything in webpack config, No extra configurations.

By using contextBridge we can resolve this issue
new BrowserWindow({
width: 1200,
height: 800,
backgroundColor: "white",
webPreferences: {
nodeIntegration: false,
worldSafeExecuteJavaScript: true,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
})
//example to display notification
ipcMain.on('notify', (_, message) => {
new Notification({title: 'Notification', body: message}).show();
})
preload.js
const { ipcRenderer, contextBridge } = require('electron');
contextBridge.exposeInMainWorld('electron', {
notificationApi: {
sendNotification(message) {
ipcRenderer.send('notify', message);
}
}
})
then using the below code in your reactjs component will trigger a native notification message
electron
.notificationApi
.sendNotification('My custom message!');

Below is the code worked for using electron-forge with react with preload script which exposes ipcRenderer API to renderer process in electron with webpack preload(FYI check package.json code below) option. Follow the link to create a project for electron-forge with react.
main.js
const { app, BrowserWindow, ipcMain, Notification } = require("electron");
const path = require("path");
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require("electron-squirrel-startup")) {
// eslint-disable-line global-require
app.quit();
}
const createWindow = () => {
console.log(__dirname, "testing");
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
worldSafeExecuteJavaScript: true,
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
},
});
// and load the index.html of the app.
mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
// Open the DevTools.
mainWindow.webContents.openDevTools();
};
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", () => {
console.log("/n demo", __dirname, "/n");
createWindow();
});
ipcMain.on("notify", (_, message) => {
new Notification({ title: "Notification", body: message }).show();
});
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
package.json
{
"name": "webex-ui",
"productName": "webex-ui",
"version": "1.0.0",
"description": "My Electron application description",
"main": ".webpack/main",
"scripts": {
"start": "electron-forge start",
"package": "electron-forge package",
"make": "electron-forge make",
"publish": "electron-forge publish",
"lint": "echo \"No linting configured\""
},
"keywords": [],
"author": {
"name": "Sathishkumar R",
"email": "rsathishtechit#gmail.com"
},
"license": "MIT",
"config": {
"forge": {
"packagerConfig": {},
"makers": [
{
"name": "#electron-forge/maker-squirrel",
"config": {
"name": "webex_ui"
}
},
{
"name": "#electron-forge/maker-zip",
"platforms": [
"darwin"
]
},
{
"name": "#electron-forge/maker-deb",
"config": {}
},
{
"name": "#electron-forge/maker-rpm",
"config": {}
}
],
"plugins": [
[
"#electron-forge/plugin-webpack",
{
"mainConfig": "./webpack.main.config.js",
"renderer": {
"config": "./webpack.renderer.config.js",
"entryPoints": [
{
"html": "./src/index.html",
"js": "./src/renderer.js",
"name": "main_window",
"preload": {
"js": "./src/preload.js"
}
}
]
}
}
]
]
}
},
"devDependencies": {
"#babel/core": "^7.14.8",
"#babel/preset-react": "^7.14.5",
"#electron-forge/cli": "^6.0.0-beta.58",
"#electron-forge/maker-deb": "^6.0.0-beta.58",
"#electron-forge/maker-rpm": "^6.0.0-beta.58",
"#electron-forge/maker-squirrel": "^6.0.0-beta.58",
"#electron-forge/maker-zip": "^6.0.0-beta.58",
"#electron-forge/plugin-webpack": "6.0.0-beta.58",
"#vercel/webpack-asset-relocator-loader": "1.6.0",
"babel-loader": "^8.2.2",
"css-loader": "^6.0.0",
"electron": "13.1.7",
"node-loader": "^2.0.0",
"style-loader": "^3.0.0"
},
"dependencies": {
"electron-squirrel-startup": "^1.0.0",
"react": "^17.0.2",
"react-dom": "^17.0.2"
}
}
app.jsx
import * as React from "react";
import * as ReactDOM from "react-dom";
class App extends React.Component {
componentDidMount() {
electron.notificationApi.sendNotification("My custom message!");
}
render() {
return <h1>contextBridge</h1>;
}
}
ReactDOM.render(<App />, document.body);
preload.js
const { ipcRenderer, contextBridge } = require("electron");
contextBridge.exposeInMainWorld("electron", {
notificationApi: {
sendNotification(message) {
ipcRenderer.send("notify", message);
},
},
batteryApi: {},
fileApi: {},
});
renderer.js
import "./index.css";
import "./app";
console.log(
'👋 This message is being logged by "renderer.js", included via webpack'
);
Also, add below in webpack.rules.js
//to avoid explicit mention of jsx when importing react components
resolve: {
extensions: [".js", ".jsx"],
},
Thanks to this page

const {ipcRenderer} = require('electron')

Related

The requested module '#firebase/rules-unit-testing' does not provide an export named 'RulesTestContext' and 'RulesTestEnvironment'

I am trying to create unit test for my security rules using the firebase emulator. I followed some tutorials but I cannot import RulesTestContext and neither RulesTestEnviroment. I tried importing the rules individually, and trying to use other ways instead of using the RulesTestEnviroment but they were deprecated.
This is my test.js:
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore";
import { initializeApp } from "firebase/app";
import {equal} from 'assert';
import { getAuth } from "firebase/auth";
import * as fs from 'fs';
import {
assertFails,
assertSucceeds,
initializeTestEnvironment,
RulesTestEnvironment,
RulesTestContext,
} from "#firebase/rules-unit-testing";
const MY_PROJECT_ID = 'fir-flutter-3ec5c';
const testUserId = 'userId1';
describe('Firestore security rules', () => {
let testEnv = RulesTestEnvironment;
let authenticatedUser = RulesTestContext;
let unauthenticatedUser = RulesTestContext;
beforeAll(async () => {
testEnv = await initializeTestEnvironment({
projectId: MY_PROJECT_ID,
firestore: {
rules: fs.readFileSync("firestore.rules", "utf8"),
host: 'localhost',
port: 8080,
}
});
});
beforeEach(async () => {
await testEnv.withSecurityRulesDisabled(context => {
const firestoreWithoutRule = context.firestore();
return firestoreWithoutRule.collection('users').doc(testUserId).set({name: 'initial
user name'});
});
authenticatedUser = testEnv.authenticatedContext(testUserId);
unauthenticatedUser = testEnv.unauthenticatedContext();
});
it('Only authenticated Users can create', async () => {
const createByAuthenticatedUser = authenticatedUser.firestore()
.collection('users').add({name: 'user name authenticated'});
await testing.assertSucceeds(createByAuthenticatedUser);
});
});
This is my package.json in the test folder:
{
"name": "test",
"version": "1.0.0",
"description": "Unit Test",
"main": "test.js",
"scripts": {
"test": "mocha --exit --timeout 100000"
},
"author": "jorge munin",
"license": "ISC",
"devDependencies": {
"#firebase/rules-unit-testing": "^2.0.5",
"mocha": "^10.1.0"
},
"type": "module"
}
I'm just trying to figure out firestore, but I believe you are trying to assign typenames to variables, which is not what you want. Just remove those.
let testEnv;
let authenticatedUser;
let unauthenticatedUser;

electron-devtools-installer not working react

I'm currently starting a new project with electron and react and I don't understand but I'm trying to use React devTools, I've tried some methods and none of them worked.
For instance, I followed here the method of electron-devtools-installer, which can be found here : https://github.com/MarshallOfSound/electron-devtools-installer
and when I launch the app the inspector still tells me
that
Download the React DevTools for a better development experience: https://reactjs.org/link/react-devtoolsYou might need to use a local HTTP server (instead of file://): https://reactjs.org/link/react-devtools-faq
Here is my main.js :
const { app, BrowserWindow, Notification, ipcMain } = require("electron");
const path = require("path");
const isDev = !app.isPackaged;
const {
default: installExtension,
REACT_DEVELOPER_TOOLS,
} = require("electron-devtools-installer");
let createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
backgroundColor: "white",
title: "TaleSmith",
icon: path.join(__dirname, "../assets/icons/appIcon.png"),
webPreferences: {
nodeIntegration: false,
worldSafeExecuteJavaScript: true,
contextIsolation: true, // is a feature that ensures that both your preload scripts and Electron internal logical tun in separate context
preload: path.join(__dirname, "preload.js"),
},
});
win.loadFile(path.join(__dirname, "..", "src", "index.html"));
isDev && win.webContents.openDevTools();
};
if (isDev) {
require("electron-reload")(__dirname, {
electron: path.join(
__dirname,
"..",
"..",
"node_modules",
".bin",
"electron",
),
});
}
app.whenReady().then(async () => {
installExtension(REACT_DEVELOPER_TOOLS)
.then((name) => console.log(`Added Extension: ${name}`))
.catch((err) => console.log("An error occurred: ", err));
createWindow();
});
ipcMain.on("notify", (_, message) => {
new Notification({
title: "Hello World",
body: message,
}).show();
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
Thanks a lot for your help !
Leverage the "dom-ready" event to initiate the dev tools instead of when the app is ready. Give this a try
const {
app,
BrowserWindow,
Notification,
ipcMain
} = require("electron");
const path = require("path");
const isDev = !app.isPackaged;
const {
default: installExtension,
REACT_DEVELOPER_TOOLS,
} = require("electron-devtools-installer");
let createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
backgroundColor: "white",
title: "TaleSmith",
icon: path.join(__dirname, "../assets/icons/appIcon.png"),
webPreferences: {
nodeIntegration: false,
worldSafeExecuteJavaScript: true,
contextIsolation: true, // is a feature that ensures that both your preload scripts and Electron internal logical tun in separate context
preload: path.join(__dirname, "preload.js"),
},
});
win.loadFile(path.join(__dirname, "..", "src", "index.html"));
if (isDev) {
require("electron-reload")(__dirname, {
electron: path.join(
__dirname,
"..",
"..",
"node_modules",
".bin",
"electron",
),
});
// Errors are thrown if the dev tools are opened
// before the DOM is ready
win.webContents.once("dom-ready", async () => {
await installExtension([REACT_DEVELOPER_TOOLS])
.then((name) => console.log(`Added Extension: ${name}`))
.catch((err) => console.log("An error occurred: ", err))
.finally(() => {
win.webContents.openDevTools();
});
});
}
};
app.on("ready", createWindow);
ipcMain.on("notify", (_, message) => {
new Notification({
title: "Hello World",
body: message,
}).show();
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});

Electronjs - BrowserWindow is not a constructor error inside renderer process

Node version: 14.18.0
OS: Mac
This is my package.json file
{
"name": "cryptic-app",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"start": "electron ./main.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"electron": "14.1.0"
}
}
This is my main.js
const electron = require('electron')
const path = require('path')
const shell = require('electron').shell
const { app, BrowserWindow, Menu } = electron
function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
enableRemoteModule: true,
nodeIntegration: true,
contextIsolation: false,
}
})
// and load the index.html of the app.
const indexFilePath = path.join( __dirname, 'src/index.html')
mainWindow.loadFile(indexFilePath)
mainWindow.webContents.openDevTools()
var menu = Menu.buildFromTemplate([
{
label: 'Menu',
submenu: [
{
label: 'Adjust notification value'
},
{
label: 'CoinMarketCap',
click() {
shell.openExternal('http://www.coinmarketcap.com/')
}
},
{
type: 'separator'
},
{
label: 'Exit',
click() {
app.quit()
}
},
]
}
])
Menu.setApplicationMenu(menu)
}
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
This is my index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<link rel="stylesheet" href="../assets/css/main.css">
</head>
<body>
<div class="row">
<div id="price-container">
<p class="subtext">Current BTC USD</p>
<h1 id="price">Loading...</h1>
</div>
<div id="goal-container">
<p>
<img src="https://s3.amazonaws.com/coursetro/tutorial_images/up.svg">
<span id="target-price">Choose a target price</span>
</p>
</div>
<div class="right-container">
<button id="notifyBtn">Notify me when...</button>
</div>
</div>
<script src="./index.js"></script>
</body>
</html>
This is my index.js file
const electron = require('electron')
const path = require('path')
const { BrowserWindow } = electron
console.log(electron)
const notifyBtn = document.getElementById('notifyBtn')
notifyBtn.addEventListener('click', function(e) {
const modalPath = path.join('file://', __dirname, 'add.html')
console.log("modalPath", modalPath)
let win = new BrowserWindow({ width: 400, height: 200, parent: top })
win.on('close', function() {
win = null
})
win.loadFile(modalPath)
win.show()
})
This is the electron object from index.js
I am getting BrowserWindow is not a constructor error inside the render process, I am not sure what is causing this issue. Can someone please help?
This is how I solved this problem :-
As I am using electron > 14, so remote resources are not available inside renderer process and not made avaolable by lectron module.
To make remote resources available to renderer process I added this module. #electron/remote
Then this is how my main.js looks now
const remote = require('#electron/remote/main')
const electron = require('electron')
remote.initialize() // Intitialize
const path = require('path')
const shell = require('electron').shell
const { app, BrowserWindow, Menu } = electron
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
show: false,
}
})
remote.enable(mainWindow.webContents) // Loads webcontents
const indexFilePath = path.join( __dirname, 'src/index.html')
mainWindow.loadFile(indexFilePath)
mainWindow.webContents.openDevTools()
var menu = Menu.buildFromTemplate([
{
label: 'Menu',
submenu: [
{
label: 'Adjust notification value'
},
{
label: 'CoinMarketCap',
click() {
shell.openExternal('http://www.coinmarketcap.com/')
}
},
{
type: 'separator'
},
{
label: 'Exit',
click() {
app.quit()
}
},
]
}
])
Menu.setApplicationMenu(menu)
}
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
Now I can can access Browser window inside my index.js file like this
const { BrowserWindow } = require('#electron/remote')
Links to refer for:-
About webcontents, read here

Function in Electron does not work but in Node does

I'm running the same function from both Electron and Node, but obtaining different results:
Invoking the function using Node from command line works fine, I get the list of connected devices:
node my_func.js
var iosDevice = require("node-ios-device");
iosDevice.devices(function (err, devices) {
if (err) {
console.error("Error!", err);
} else {
console.log(devices);
}
});
But putting the same chunk of code in main.js in Electron
(it's not in any other renderer file and it is just invoked from command line using the standard: $ npm run start),
yields the following outcome:
main.js
const { app, BrowserWindow } = require("electron");
var iosDevice = require("node-ios-device");
iosDevice.devices(function (err, devices) {
if (err) {
console.error("Error!", err);
} else {
console.log(devices);
}
});
// SET ENVIRONTMENT
process.env.NODE_ENV = "development";
// process.env.NODE_ENV = "production";
const isDev = process.env.NODE_ENV !== "production" ? true : false;
// CHECK PLATFORM
const isMac = process.platform === "darwin" ? true : false;
let mainWindow;
function createMainWindow() {
mainWindow = new BrowserWindow({
title: "test",
width: 700,
height: 195,
icon: "./assets/icons/Icon_256x256.png",
resizable: isDev ? true : false,
backgroundColor: "white",
show: false,
webPreferences: {
nodeIntegration: true,
// sandbox: true,
// contextIsolation: false,
},
});
mainWindow.loadFile("./app/index.html");
mainWindow.webContents.on("did-finish-load", function () {
mainWindow.show();
});
}
app.on("ready", () => {
createMainWindow();
});
app.on("window-all-closed", () => {
if (!isMac) {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createMainWindow();
}
});
The console does not show any result
Apparently, three instances of the app get created, 3 app icons pops up in Dock:
Three app icons show up
this is the package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"author": "Viking",
"license": "ISC",
"devDependencies": {
"electron": "^11.4.4"
},
"dependencies": {
"node-ios-device": "^1.9.2"
}
}
and requiring the npm "node-ios-device" package does not present any issue.
Any idea about how I can accomplish the same task using Electron instead Node?
Thank you.
UPDATE
After trying difference things this is the most close I got to a solution:
I moved the function to another file and I call it from the main.js file spawning a child process and invoking the function using node:
ipcMain.on("dev:getinfo", (event, options) => {
let child_proc;
let devices;
child_proc = spawn("node", ["device.js"]);
child_proc.stdout.on("data", (data) => {
devices = `${data}`;
});
child_proc.on("exit", function (code, signal) {
console.log(devices);
});
});
And it works, in development...
but I have the feeling that it's not going to work in production since the users I'd like to distribute this app do not have Node.js installed and I don't know how I could bundle electron in such way that the users don't need to have Node.js installed.
So an issue was resolved but another one showed up 😐
Further info about my comment above...
If you want to get access to the iOSdevices from the main process to the renderer (that is the electron frontend or the webpage), try to use the
webContents or the ipcMain/ipcRenderer event emitters.
// In the main process.
const { app, BrowserWindow } = require("electron");
const { iosDevice } = require("node-ios-device");
-- previous snips --
let win = null
app.whenReady().then(() => {
win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL(`file://${__dirname}/index.html`)
win.webContents.on('did-finish-load', () => {
let devices = iosDevice.devices(function (err, devices) {
if (err) {
console.error("Error!", err);
} else {
console.log(devices);
return devices;
}
});
win.webContents.send('send-devices', devices);
})
})
Then in your index.html..
<!-- index.html -->
<html>
<body>
<script>
require('electron').ipcRenderer.on('send-devices', (event, message) => {
console.log(message) // Prints the devices
})
</script>
</body>
</html>
// https://www.electronjs.org/docs/api/web-contents#contentssendchannel-args

Always compile certain files when compiling a NX Workspace NestJS Project using Angular CLI

I have a project, which is set up as an nx-workspace, this includes a NestJS project called sync. I'm trying to use this on Lambda with multiple functions, I have this working outside an NX Workspace, which compiles a full directory, however in an NX Workspace it compiles into the main.js file, which doesn't include the two Lambda files which call the NestJS framework.
I think the issue lies here:
"sync": {
"root": "apps/sync",
"sourceRoot": "apps/sync/src",
"projectType": "application",
"prefix": "sync",
"schematics": {},
"architect": {
"build": {
"builder": "#nrwl/node:build",
"options": {
"outputPath": "dist/apps/sync",
"main": "apps/sync/src/main.ts",
"tsConfig": "apps/sync/tsconfig.app.json",
"assets": ["apps/sync/src/assets"],
"scripts": ["apps/sync/src/app/lambdas/**/*"]
},
"configurations": {
"production": {
"optimization": true,
"extractLicenses": true,
"inspect": false,
"fileReplacements": [
{
"replace": "apps/sync/src/environments/environment.ts",
"with": "apps/sync/src/environments/environment.prod.ts"
}
]
}
}
},
"serve": {
"builder": "#nrwl/node:execute",
"options": {
"buildTarget": "sync:build"
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"apps/sync/tsconfig.app.json",
"apps/sync/tsconfig.spec.json"
],
"exclude": ["**/node_modules/**", "!apps/sync/**/*"]
}
},
"test": {
"builder": "#nrwl/jest:jest",
"options": {
"jestConfig": "apps/sync/jest.config.js",
"tsConfig": "apps/sync/tsconfig.spec.json",
"passWithNoTests": true
}
}
}
Which always compile a JS file based on this file:
import { Logger } from '#nestjs/common';
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app/app.module';
declare const module: any;
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
logger: ['log', 'error', 'warn', 'debug', 'verbose'],
});
const port = process.env.PORT || 3010;
await app.listen(port, () => {
Logger.log('Listening at http://localhost:' + port);
});
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => app.close());
}
}
bootstrap();
However, I have two files which need to be included, as they run each function:
import { Handler } from 'aws-lambda';
import { NestFactory } from '#nestjs/core';
import { AppModule } from '../app.module';
import { FooController } from '../foo/foo.controller';
async function bootstrap() {
const app = await NestFactory.createApplicationContext(AppModule);
return app;
}
export const syncFooHandler: Handler = async (event) => {
const app = await bootstrap();
const fooService = app.get(FooController);
return await fooService.sync(event);
};
import { Handler } from 'aws-lambda';
import { NestFactory } from '#nestjs/core';
import { AppModule } from '../app.module';
import { BarController } from '../bar/bar.controller';
async function bootstrap() {
const app = await NestFactory.createApplicationContext(AppModule);
return app;
}
export const syncStudentsHandler: Handler = async (event) => {
const app = await bootstrap();
const barService = app.get(BarController);
return await barService.sync(event);
};
But these files are not included in main.js file which is compiled.

Categories

Resources