How can the variable be inaccessible? - javascript

I have a NextJS app with some server side code that gets bundled with Webpack (default NextJS setup). When running this with the product build, I get the following error:
ReferenceError: Cannot access 'providers' before initialization
Looking at the generated bundle at the lines referenced by the error, I can see this:
const providers = {
[_myapp_webapp_types__WEBPACK_IMPORTED_MODULE_0__.ProviderType.Provider0]: _provider0__WEBPACK_IMPORTED_MODULE_1__/* .provider0 */ .d,
[_myapp_webapp_types__WEBPACK_IMPORTED_MODULE_0__.ProviderType.Provider1]: _provider1__WEBPACK_IMPORTED_MODULE_2__/* .provider1 */ .S
};
function getProvider(config) {
return providers[config.type];
}
In my head, there can be nothing stopping providers from being initialised when the getProvider function is called. What is going on here, and what can I do about it?
EDIT:
The code is within a separate file that gets imported by another file that calls the getProvider-function. This means (in my head) that the providers variable without doubt should be initialised as soon as the function is called (from outside the module).
(Also, everything works just fine when running locally)

Turns out the problem was solved by updating to the latest minor upgrade of NextJS. (So this was possibly a bug somewhere down the line.)

Related

How to pass variables from electron to the angular behind

I want to make a website and desktop app with one single codebase. But because there are some minor differences, I need to know in the angular app whether the app got called from the web or from electron.
In the main.js I have already tried:
Putting a URL parameter in the loadFile function like this:
win.loadFile('dist/project/index.html?electron=true')
but then it doesn't find the file anymore.
I have tried to make a second 'index.html':
win.loadFile('dist/project/electron.html')
but that html does not get compiled with angular.
In your angular side you can check the process global constant, the package #types/node must be instaled
cont inElectron = process.versions.hasOwnProperty('electron');
console.log(inElectron);
// true if the app is running in electron, otherwise false
https://stackblitz.com/edit/angular-lrgkgv

Require statement inside an if runs even if it returns false

I have added a require statement to require the ws library inside an if statement so that it will be imported only if its not the browser. For example, require ws only for the tests.
if (!process.browser) {
webSocketLinkConfig.webSocketImpl = require('ws');
}
But the problem is, even though the rest of the assignment webSocketLinkConfig.webSocketImpl doesn't happen, the require gets executed and I get a warning in the browser saying Module not found: Can't resolve 'bufferutil' in '/Users/pubudu/Projects/FleetManager/fm-dash-front/node_modules/ws/lib'
Any idea what's happening and how to fix it?
This is a react app built with create-react-app.
I have not used process.broswer before, so it may be possible you do not have it set. I made a sandbox for getting whether or not you are running in a browser by using navigator.
The navigator object contains information about the browser. - w3schools
if (!navigator) {
webSocketLinkConfig.webSocketImpl = require('ws');
}
Here is a CodeSandbox example which (using console) shows how you can use navigator to tell if you're running your code in a browser. Hope this helps.

Parent view not setting global variable on <webview> in Electron after updating

I am trying to require a module in a guest page (angular controller).
When the application used an older version of node (0.30.5) it worked perfectly well. However i've had to upgrade electron to the latest version (0.37.6), and ive updated all uses of ipc in the electron application, so that it's now ipcMain and ipcRenderer.
Previously the angular controller managed to require the module using:
var ipc = window['require']('ipc');
So i thought that changing it to:
var ipcRenderer = window['require']('electron').ipcRenderer;
However that does not work and it states that window.require is not a function. I've tried multiple times to get it to work with other methods, however nothing works so far.
The problem is that require is undefined, however require is set in the html file that contains the <webview>, so it should be defined.
The <webview> goes to a URL which returns a <div> that uses angular.
The angular controller that is used in that <div> is no longer working, as the module I need is the first thing to be set in the file, and it is undefined
EDIT:
I can now see that the property that I set in the html is visible in the application debugger, however it does not appear in the webview debugger.
So I can only assume the parent view does not pass on the value to the <webview>. So if anyone knows why it doesn't pass on the value or what I need to do to set it, I would appreciate any information.
So as of the current version of Electron (0.37.6) the way to set a global variable is to specify a preload script on the preload attribute on the <webview> tag. For example in the preload script:
window['ipcRenderer'] = require('electron').ipcRenderer;
This will allow the guest page that the <webview> is displaying, to use the ipcRenderer. It seems like the previous method i was using, which was setting the global variable in the parent view HTML, does not work anymore
It's a quite old way to require electron modules. Here's the new one:
var ipcRenderer = require('electron').ipcRenderer;

How to get my 404 page to show after upgrade of Sails.js to 0.10.x?

I've upgraded my Sails.js app to 0.10.x and now when I point my browser at a non-existent route such as http://localhost:1337/notfound instead of my views/404.jade being served up I just get a bit of JSON
{
"status": 404
}
I built a default new sails app sails new dummy --template=jade just to compare and contrast with what I have in my existing app, and the only obvious difference I see is that in dummy/config/ there is a file called http.js
I've copied that file over to my app but it's made no difference.
I've also ensured that the tasks in dummy/tasks are identical to my own app's tasks.
In dummy/config/routes.js it says
Finally, if those don't match either, the default 404 handler is triggered.
See config/404.js to adjust your app's 404 logic.
Which is obviously out of date as 0.10.x apps use the api/responses mechanisms.
So I am at rather a loss as to how to get this to work.
I am using 0.10.0-rc8 (and I have confirmed that this is the same in my dummy app as well as my actual app)
Well I've fixed this but I have no idea why it was happening.
To fix it I created a new project as per the method described in my question, but with the same name as my existing project, then, file-by-file, I painstakingly moved across everything specific to my app, taking care to leave in place anything new generated by sails.
Once I'd done that I ran my tests - all passed - and then sails lift and tried it, and yay, everything worked and I got my 404 error page back.
I committed my changes and then carefully picked through a comparison of what had changed.
Alas nothing at all stands out, so, while I have solved my problem, I have no idea what the original cause was.
From the section in the migration guide on "Custom Responses":
In v0.10, you can now generate your own custom server responses. See
here to learn how. Like before, there are a few that we automatically
create for you. Instead of generating myApp/config/500.js and other
.js responses in the config directory, they are now generated in
myApp/api/responses/. To migrate, you will need to create a new v0.10
project and copy the myApp/api/responses directory into your existing
app. You will then modify the appropriate .js file to reflect any
customization you made in your response logic files (500.js,etc).
Basically, v0.10.x gives you more freedom in how things like res.notFound, res.serverError and even res.ok() (success response) work, but you need to copy over the new api/responses folder to migrate.
I had the same issue but was using 0.9.x. Probably a better solution but I outputted a view instead of JSON in all cases.
Update config/404.js to replace res.json() with res.view():
if (err) {
//return res.json(result, result.status); }
return res.view('404') // <-- output the 404 view instead
}
Then, just make sure in your routes.js file it will redirect the /404. Place the following at the bottom of your routes.js file:
'/*': {
view: '*'
},

How can I edit on my server files without restarting nodejs when i want to see the changes?

I'm trying to setup my own nodejs server, but I'm having a problem. I can't figure out how to see changes to my application without restarting it. Is there a way to edit the application and see changes live with node.js?
Nodules is a module loader for Node that handles auto-reloading of modules without restarting the server (since that is what you were asking about):
http://github.com/kriszyp/nodules
Nodules does intelligent dependency tracking so the appropriate module factories are re-executed to preserve correct references when modules are reloaded without requiring a full restart.
Check out Node-Supervisor. You can give it a collection of files to watch for changes, and it restarts your server if any of them change. It also restarts it if it crashes for some other reason.
"Hot-swapping" code is not enabled in NodeJS because it is so easy to accidentally end up with memory leaks or multiple copies of objects that aren't being garbage collected. Node is about making your programs accidentally fast, not accidentally leaky.
EDIT, 7 years after the fact: Disclaimer, I wrote node-supervisor, but had handed the project off to another maintainer before writing this answer.
if you would like to reload a module without restarting the node process, you can do this by the help of the watchFile function in fs module and cache clearing feature of require:
Lets say you loaded a module with a simple require:
var my_module = require('./my_module');
In order to watch that file and reload when updated add the following to a convenient place in your code.
fs.watchFile(require.resolve('./my_module'), function () {
console.log("Module changed, reloading...");
delete require.cache[require.resolve('./my_module')]
my_module = require('./my_module');
});
If your module is required in multiple files this operation will not affect other assignments, so keeping module in a global variable and using it where it is needed from global rather than requiring several times is an option. So the code above will be like this:
global.my_module = require ('./my_module');
//..
fs.watchFile(require.resolve('./my_module'), function () {
console.log("Module changed, reloading...");
delete require.cache[require.resolve('./my_module')]
global.my_module = require('./my_module');
});
Use this:
https://github.com/remy/nodemon
Just run your app like this: nodemon yourApp.js
There should be some emphasis on what's happening, instead of just shotgunning modules at the OP. Also, we don't know that the files he is editing are all JS modules or that they are all using the "require" call. Take the following scenarios with a grain of salt, they are only meant to describe what is happening so you know how to work with it.
Your code has already been loaded and the server is running with it
SOLUTION You need to have a way to tell the server what code has changed so that it can reload it. You could have an endpoint set up to receive a signal, a command on the command line or a request through tcp/http that will tell it what file changed and the endpoint will reload it.
//using Express
var fs = require('fs');
app.get('reload/:file', function (req, res) {
fs.readfile(req.params.file, function (err, buffer) {
//do stuff...
});
});
Your code may have "require" calls in it which loads and caches modules
SOLUTION since these modules are cached by require, following the previous solution, you would need a line in your endpoint to delete that reference
var moduleName = req.params.file;
delete require.cache[moduleName];
require('./' + moduleName);
There's a lot of caveats to get into behind all of this, but hopefully you have a better idea of what's happening and why.
What's “Live Coding”?
In essence, it's a way to alter the program while it runs, without
restarting it. The goal, however, is to end up with a program that
works properly when we (re)start it. To be useful, it helps to have an
editor that can be customized to send code to the server.
Take a look: http://lisperator.net/blog/livenode-live-code-your-nodejs-application/
You can also use the tool PM2. Which is a advanced production process tool for node js.
http://pm2.keymetrics.io/
I think node-inspector is your best bet.
Similar to how you can Live Edit Client side JS code in Chrome Dev tools, this utilizes the Chrome (Blink) Dev Tools Interface to provide live code editing.
https://github.com/node-inspector/node-inspector/wiki/LiveEdit
A simple direct solution with reference to all answers available here:
Node documentation says that fs.watch is more efficient than fs.watchFile & it can watch an entire folder.
(I just started using this, so not really sure whether there are any drawbacks)
fs.watch("lib", (event_type, file_name) => {
console.log("Deleting Require cache for " + file_name);
delete require.cache[ require.resolve("./lib/" + file_name)];
});

Categories

Resources