This seems really dumb, but I need help for importing some source code into the renderer process in electron:
I have an electron app:
index.html (loads window.js with a tag)
- index.js
- window.js
- useful_functions.js
In window.js, I want to import some functions from useful_functions.js, so I've tried the following:
// fails with: Uncaught SyntaxError: Unexpected identifier
import { very_useful } from './useful_functions.js';
// fails with: Uncaught ReferenceError: require is not defined
const { very_useful } = require('./useful_functions.js');
// fails with: Uncaught ReferenceError: require is not defined
require('electron').remote.require('./useful_functions.js')
I also tried the nodeIntegration flag, but that didn't help either
Note: I'm not trying to import npm modules but my own code, in an other file right next to it.
I'm looking for examples, but I only find super small samples with just the basic files. (Or huge apps like atom that would take me a while to figure out)
I don't have webpack setup for this project yet, but I'm sure there is a simpler way to do this very basic task...
Thanks for any help.
In index.html, use require() instead of loading window.js with a tag, i.e., replace:
<script src="window.js"></script>
with:
<script>require('./window.js');</script>
Then, in window.js, the following statement should work too:
const { very_useful } = require('./useful_functions.js');
Note that nodeIntegration: true is needed in the options passed to new BrowserWindow() anyway:
webPreferences:
{
nodeIntegration: true
}
See:
Node Modules
Functions and objects are added to the root of a module by
specifying additional properties on the special exports object.
Variables local to the module will be private, because the module is
wrapped in a function by Node.js (see module wrapper).
Module Wrapper
Before a module's code is executed, Node.js will wrap it with a
function wrapper that looks like the following:
(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});
Related
I am trying to add a custom favicon to my NestJs documentation. However, I am a bit lost on how the path file gets resolved and not sure how to achieve this.
I am using nestjs/swagger module version 3.1.0 and trying to pass the path file like so when initializing the Swagger Module.
My main.ts file
SwaggerModule.setup('/v1/docs', app, document, {
customCss: CUSTOM_STYLE,
customSiteTitle: 'My API Documentation',
customfavIcon: './public/favicon.jpg'
});
Searched on the github issues and didn't find anything useful. And as you can see from the code I was able to modify the CSS styles, but I cannot figure out how to make the favicon custom.
Appreciate any help
I have added the custom favicon to my swagger docs using following:
The first thing you make sure is, in your main.ts, the app is initialized with the following:
const app: NestExpressApplication = await NestFactory.create(...)
To serve static content you must initialize your app with NestExpressApplication.
The next thing is to allow the Nest application to look for public content using the following in your main.ts after initialization:
app.useStaticAssets(join(__dirname, '..', 'public'));
Also, create a public directory in your root of the application and paste your favicon.jpg file in it.
Now its time to initialize the Swagger in main.ts
SwaggerModule.setup('/v1/docs', app, document, {
customCss: CUSTOM_STYLE,
customSiteTitle: 'My API Documentation',
customfavIcon: '../favicon.jpg'
});
You must give a relative path to the root of the application like ../favicon.jpg in case our main.ts is in src folder in root of the application.
Alternative solution, just host your favicon and reference it with external url
SwaggerModule.setup('api', app, getSwaggerDocument(app), {
...
customfavIcon:
'https://[your-bucket-url].com/.../anything.png',
});
To iterate on pravindot17's answer, now there's the #nestjs/serve-static package for hosting static files. Which avoid us from type-casting the Nest.js client and relying on our implicit assumption that we're running an Express-backed Nest.js server.
After installing the package, you hook it into your src/app.module.ts. This configuration expects that the root of your project has a /public/ folder where you store your static assets.
import { Module } from '#nestjs/common';
import { ServeStaticModule } from '#nestjs/serve-static';
import { join } from 'path';
#Module({
imports: [
// Host static files in ../public under the /static path.
ServeStaticModule.forRoot({
/**
* Config options are documented:
* https://github.com/nestjs/serve-static/blob/master/lib/interfaces/serve-static-options.interface.ts
*/
rootPath: join(__dirname, '..', '..', 'public'),
serveRoot: '/static',
}),
// ...
})
export class AppModule {}
Now my own preference is using an absolute path rather than relative, as it makes it independent from the path we picked to host our API documentation under.
SwaggerModule.setup('/v1/docs', app, document, {
customfavIcon: '/static/favicon.jpg'
});
One last note is that this configuration hosts static files from /static/*, this is done to prevent that API calls to non-existing endpoints show an error message to the end-user that the static file cannot be found.
Otherwise, all 404's on non-existing endpoints will look something like:
{"statusCode":404,"message":"ENOENT: no such file or directory, stat '/Users/me/my-project/public/index.html'"}
Please help...I am trying to get openPGP.js working in an existing ASP.Net MVC Web Application.
I first started by adding the following html script tags:
<script src="#Url.Content("~/Scripts/openpgp.min.js")"></script>
<script src="#Url.Content("~/Scripts/openpgp.worker.min.js")"></script>
and I got this error on loading my page:
ReferenceError: importScripts is not defined
So I did some research and added RequireJS to my page, like so:
<script data-main='#Url.Content("~/Scripts/openpgp.min.js")' src="#Url.Content("~/Scripts/require.js")"></script>
Then in the event handler in which I intend to run my decryption logic, I have the following code:
async function decryptBBRecording(commId) {
var openpgp = require(['openpgp']);
await openpgp.initWorker({ path: 'openpgp.worker.js' }) // set the relative web worker path
...
...
...
}
and it is on that "await" line that I am getting
TypeError: openpgp.initWorker is not a function
I'm thinking this is because I have not loaded the openpgp.worker.min.js file. But when I do so via script tag, I get the following errors:
ReferenceError: importScripts is not defined
and when I do so via require(["#Url.Content("~/Scripts/openpgp.worker.min.js")"]); I get this:
Error: Script error for "openpgp"
ReferenceError: importScripts is not defined
Please can you provide me with guidance on how to get this working?
Answer provided here.
You don't have to include openpgp.worker.min.js on the page directly. You also shouldn't need require.js and the call to require. Just include openpgp.min.js on the page, it will globally define openpgp, and then call openpgp.initWorker as you are doing.
This question already has answers here:
Mismatched anonymous define() module
(8 answers)
Closed 5 years ago.
Let's say I have 2 files: test1.ts and test2.ts. This is the content of test1:
export const x = 1
This is the content of test1:
import { x } from './test2'
alert(x);
When I run the application, I get this error: Uncaught ReferenceError: exports is not defined at test1.js:2.
According to other posts, this error is caused by the fact that web browsers don't support export, and require(...). To solve it, one of the solution would be to use something like RequireJs.
So I've done some readings. This article has been the easiest for me to understand.
I've added this line in the _Layout.cshtml file.
<script src="~/Scripts/require.js"></script>
Create a config file.
requirejs.config({
baseUrl: '/Scripts/js'
});
I've put test1 and test2 in the /Scripts/js folder.
Run the application, but still get the same error: Uncaught ReferenceError: exports is not defined at test1.js:2.
How to fix the error using RequireJs?
Thanks for helping.
EDIT
The solution doesn't have to be RequireJs but anything the fix the problem. There are so many great tutorial on typescript, but they all assume that people are using node or angularjs. All I need is to add some typescript to my asp.net mvc app. As long it was one file, things were fine. Now I'd like to re-use some of the code, thus I organized them in different files. Unfortunately, I can't move forward because of that error. I've been sitting there for 3 days now.
EDIT 2
I've added commonJs to amd as you suggested by #artem,
{
"compilerOptions": {
"module": "amd",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true
}
}
now I'm getting this error.
Uncaught Error: Mismatched anonymous define()
module: function (require, exports, CommonTypes_1) {
//...
It seems like this question is dealing with the same issue. Should I put this code in a new file?
I know this is a little old, but just ran into this problem. Here's how I solved it.
This post was very helpful: https://volaresystems.com/blog/post/2014/05/27/Adding-RequireJS-to-an-ASPNET-MVC-project
First, add require.js to your BundleConfig.cs. Mine looks like this:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/require.js"));
Next, make sure _Layout.cshtml renders "scripts" section after your bundles. Mine looks like this:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
Then in your view, render the scripts section like below. My Index.cshtml looks like this:
#section scripts
{
<script>
require(["Scripts/Init"],
function (Init) {
Init.Start();
}
);
</script>
}
My ~/Scripts/Init.ts file looks like this:
import * as DataBind from "./DataBind"
export function Start() {
DataBind.SetAllDatabinds(null);
}
From there, you can load in all your modules as needed. The important thing I found is to not have any "loose code" in your TypeScript files (i.e. the "alert(x)" in the example). Everything should be exported.
I have an aurelia application running in electron. My source files are typescript and I have ambient typings for electron and node.
Because I know I'm compiling for use on electron, I am transpiling my typescript to es6 and with System module loading; this means I can turn system.js's transpiler off. I'm using system.js and jspm because that is approach Aurelia has been pushing.
So in my ts files: I would like to be able to do:
import {remote} from 'electron';
Unfortunately, system.js does not know anything about the module electron and fails during runtime. TypeScript on the other hand is perfectly happy because I've set up the typings for electron and node; I get full intellisense in VSCode too.
note: if you attempt to do var electron = require('electron'); in the header, system.js interferes with it and it fails to load. You can place that 'require('electron')' within a class or function and it will work, but I don't find this ideal.
Question: How can I get system.js to correctly return the 'electron' module that is only available when you run the app in electron itself?
A solution --hopefully there is a better way-- I've come up with is to shim the electron module for system.js and link it directly to the contents of require('electron'):
electron.js
System.register([], function (exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var electron;
return {
setters: [],
execute: function () {
electron = require('electron');
exports_1("default", electron);
Object.keys(electron).forEach(function (key) {
exports_1(key, electron[key]);
});
}
}
});
this effectively wraps the internal electron module and allows system.js to know about it. It works; but hopefully there is a more elegant/built-in way that others know of.
You don't need any mappings or changes to the typescypt as import {remote} from 'electron' will attempt to resolve electron.js as a last resort.
I am doing some unit test in casperjs and I got stuck: how do include dependency file from the test itself? Included javascript file can be just a bunch of functions, and does not declare any interface (module.exports = ... etc).
I know I can include from the command line
$ casperjs test --include=./my-mock.js mytest.js
but how can I include files from the test itself?
Putting following on the top does not work for me... my_mock is undefined
casper.options.clientScripts = ["./my-mock.js"]; //push() does not help either
//mytest.js is below
// ------------------------------------------
casper.test.begin('ajax mock test', function suite(test) {
my_mock.setFetchedData("bla");
my_mock.doRequest();
test.assertEquals( ......);
test.done();
});
// ------------------------------------------
CasperJS version 1.1.0-DEV using phantomjs version 1.9.1
Using phantom.injectJs method is the best option I've found so far. E.g. you're having two files in your directory: "tests.js" and "settings.js". You want to include "settings.js" into "test.js". The first thing you should do with your "test.js" is write the following:
phantom.injectJs('settings.js');
casper.test.begin(...
...
The reason that clientScripts isn't working is that it is loaded on each page load, so you don't have access to the objects/functions defined in the file outside of a casper.evaluate() call.
You can use require() to pull in modules, however you may need to modify your included script to work with this method.
Here is what I changed your mytest.js to:
var my_mock = require('my-mock');
casper.test.begin('ajax mock test', function suite(test) {
my_mock.setFetchedData("bla");
my_mock.doRequest();
//test.assertEquals( ... );
test.done();
});
And this is a quick script (my-mock.js) that I threw together to print out when you use the functions you provided.
module.exports = {
setFetchedData: function(a) {
console.log('setFetchedData: ' + a);
},
doRequest: function() {
console.log('doRequest');
}
};
I found useful this sample demonstrating --includes option:
$ casperjs test tests/ --pre=pre.js --includes=inc.js --post=post.js
to load functions that you often use in your tests.