nextjs import but don't invoke function throws Module not found: Error: Can't resolve 'dns' - mongodb

My project(NextJS) was working fine and suddenly I am experiencing the issue ModuleNotFoundError. Particularly in the case of dynamic routing of nextJs.
Error I see is: Module not found: Error: Can't resolve 'dns'
In the pages directory pages/programs/[programtype]/[program].jsx when mongo is imported, it throws:
ModuleNotFoundError: Module not found: Error: Can't resolve 'dns' in 'node_modules/mongodb/lib'
Full error dump:
ModuleNotFoundError: Module not found: Error: Can't resolve 'dns' in '/project-path/node_modules/mongodb/lib'
at /project-path/node_modules/webpack/lib/Compilation.js:925:10
at /project-path/node_modules/webpack/lib/NormalModuleFactory.js:401:22
at /project-path/node_modules/webpack/lib/NormalModuleFactory.js:130:21
at /project-path/node_modules/webpack/lib/NormalModuleFactory.js:224:22
at /project-path/node_modules/neo-async/async.js:2830:7
at /project-path/node_modules/neo-async/async.js:6877:13
at /project-path/node_modules/webpack/lib/NormalModuleFactory.js:214:25
at /project-path/node_modules/enhanced-resolve/lib/Resolver.js:213:14
at /project-path/node_modules/enhanced-resolve/lib/Resolver.js:285:5
at eval (eval at create (/project-path/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:13:1)
at /project-path/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js:44:7
at /project-path/node_modules/enhanced-resolve/lib/Resolver.js:285:5
at eval (eval at create (/project-path/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:13:1)
at /project-path/node_modules/enhanced-resolve/lib/Resolver.js:285:5
at eval (eval at create (/project-path/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:25:1)
at /project-path/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js:67:43

The problem
This is a subtle problem with server-side code in Next.js.
The error is clear - you're trying to execute server side code (mongo query) in a client side code. But the cause is not obvious, because with Next.js you should be able to call Mongo from your components.
The cause
Next.js throws this error because you are importing your mongo code without using it.
It sounds weird but it is true.
How to avoid it
To avoid this error just remove any server-side code import in your components if you don't use it in getServerSideProps.
It sounds even more weird but it is true.
Good and bad examples
This works fine:
import { findUsers } from '../lib/queries'
function Home({ users }) {
return (
<h1>Users list</h1>
//users.map and so on...
)
}
export async function getServerSideProps() {
const users = await findUsers()
return {
props: {
users: users
}
}
}
export default Home
While this will throw the error:
import { findUsers } from '../lib/queries'
function Home({ users }) {
return (
<h1>Users list</h1>
//users.map and so on...
)
}
export async function getServerSideProps() {
// call disabled to show the error
// const users = await findUsers()
return {
props: {
users: [] //returning an empty array to avoid other errors
}
}
}
export default Home

Keep your server-side coding modules (for e.g: models, database connection maker) outside of the Page directory.
For reference: https://nextjs.org/docs/messages/prerender-error

If you're getting this error with Next-js auth, make sure your "lib" folder is in the root directory.
Here's the structure

my problem was that i used a function in initialprops wich was exported via module.exports instead of export default

I created a directory called 'api-lib' in my project root directory to add my queries and that caused this error to appear.
And I solved it by moving my 'api-lib' directory into the main 'src' directory.

My issue was exporting getServerSideProps with all of it's server side operations from a component, where it should only be placed and exported from a PAGE component.
Moving getServerSideProps to the main page component and just drilling down what I needed to the child component solved it for me.

Related

NetSuite SuiteScript - Constants And Inclusion

I have a NetSuite SuiteScript file (2.0) in which I want to include a small library of utilities I've built. I can do that fine, and access the functions in the included library. But I can't access the constants I've defined in that library - I have to re-declare them in the main file.
Here's the main file:
define(['N/record', 'N/search', './utils.js'],
function (record, search, utils) {
function pageInit(scriptContext) {
isUserAdmin = isCurrentUserAdmin(contextRecord);
if (isUserAdmin) {
alert('Administrator Role ID is ' + ADMINISTRATOR_ROLE);
// Do something for Admin users
}
return;
}
return {
pageInit: pageInit
};
});
You can see I include the file ./utils.js in it. Here's utils.js:
const ADMINISTRATOR_ROLE = 11;
function isCurrentUserAdmin(currentRecord) {
return ADMINISTRATOR_ROLE == nlapiGetRole();
}
That's the entire file - nothing else.
In the main file, the call to the function isCurrentUserAdmin works fine. It correctly tells me whether the current user is an admin. Note that I don't have to preface the call to isCurrentUserAdmin with utils. (utils.isCurrentUserAdmin doesn't work - it gives me the error JS_EXCEPTION TypeError utils is undefined). But when the code gets to the line that uses ADMINSTRATOR_ROLE, I get the error JS_EXCEPTION ReferenceError ADMINISTRATOR_ROLE is not defined. BTW, if I put the constant definition of ADMINISTRATOR_ROLE in the main file instead of utils.js, I get the same error when utils.js tries to use it. The only way I can get it to work is if I have the line defining the constant in both files.
Why does the inclusion work for the function, but not the constant? Am I including the library wrongly? I thought I'd have to use it as utils.isCurrentUserAdmin rather than just isCurrentUserAdmin, but to my surprise that's not the case, as I say above.
If you have utils.js like below, you can use utils.ADMINISTRATOR_ROLE and utils.isCurrentUserAdmin() in your main file.
/**
*#NApiVersion 2.0
*/
define ([],
function() {
const ADMINISTRATOR_ROLE = 11;
function isCurrentUserAdmin() {
// check here
}
return {
ADMINISTRATOR_ROLE: ADMINISTRATOR_ROLE,
isCurrentUserAdmin: isCurrentUserAdmin
};
});
Try
define(['N/record', 'N/search', 'SuiteScripts/utils']
You need to make sure any member you need to access in another module needs to be exported in the source module using the return statement

this$store function is undefined

I am trying to use vuex's store to make some API calls but after installing vuex, importing store to my files and following other stack overflow answers, like making sure vuex is installed, if i am exporting my store file with " Vuex.Store" and etc but my loadCalls function is still not working.
This is the error i get:
this.$store.loadCalls is not a function
Here is my function and how i am trying to call it, it is declared in my ACTIONS section of my store.js file.
loadCalls() {
axios
.get("/some/calls")
.then(res => {
console.log(res)
});
},
I try using it in my beforeMount() when my component loads:
beforeMount(){
this.$store.loadCalls();
}
What am i doing wrong here?
If you defined an action like this:
actions: {
loadCalls() {
// ...
}
}
Then you would call it like this:
this.$store.dispatch('loadCalls');
Actions aren't exposed directly, you call them using dispatch.
https://vuex.vuejs.org/guide/actions.html#dispatching-actions

Can't make webpack ProvidePlugin work

I have file where I export object
let myHelper = {
hello() {
console.log('hello')
}
}
export default myHelper;
In webpack I could set alias, and this work for e.g. import myHelper from 'myHelper':
alias: {
myHelper: path.resolve(__dirname, 'app/folder/myHelper.js')
}
But I can't require it properly in ProvidePlugin. I've tried many possible combinations from other answers...
myHelper: path.resolve(__dirname, 'app/folder/myHelper.js')
or
myHelper: ['app/folder/myHelper.js', 'default']
Webpack doesn't throw 'cannot find module' on start. but I've got 'myHelper' is undefined when trying to use it. What could be wrong?
I thought I could require it on ProvidePlugin and than just use without require anywhere else.

Problems in lesson from angular-meteor.com

I start to learn angular2 and meteor, from http://angular-meteor.com/tutorials/angular2/3-way-data-binding
And in 3th lesson i have 2 error in console:
refreshingclient/app.ts (18, 11): Generic type 'Array<T>' requires 1 type argument(s).
client/app.ts (20, 19): Cannot find name 'zone'.
when i added some documents to Mongo from command line, they not appear on page.
and my app.ts file:
/// <reference path="../typings/angular2-meteor.d.ts" />
import {Component, View, NgFor} from 'angular2/angular2';
import {Parties} from 'collections/parties';
import {bootstrap} from 'angular2-meteor';
#Component({
selector: 'app'
})
#View({
templateUrl: 'client/app.html',
directives: [NgFor]
})
class Socially {
parties: Array;
constructor() {
Tracker.autorun(zone.bind(() => {
this.parties = Parties.find().fetch();
}));
}
}
bootstrap(Socially);
what is the problem?
In the client/app.ts file, the instructions (http://angular-meteor.com/tutorials/angular2/3-way-data-binding) show:
class Socially {
parties: Mongo.Cursor;
constructor () {
this.parties = Parties.find();
}
}
It should actually be:
class Socially {
parties: Mongo.Cursor<Object>;
constructor () {
this.parties = Parties.find();
}
}
Notice <Object> has been added after Mongo.Cursor.
If you go to Step 4, there is a link to download a zip file of the code (https://github.com/Urigo/meteor-angular2.0-socially/archive/step_03.zip). You'll see in there that the code is correct.
kuka-
main.ts and load_parties.ts are there just to create data in your db if there is none. So if adding those files made it work, there must have been something wrong with the data you created from the command line. My guess is the data you added from the command line went to the wrong collection (i.e. Party vs party). You can check your collections and data by typing
meteor mongo
at the root of your project to get a mongo prompt. Then at the mongo prompt type
show collections
This will display all collections in your db. You should have one called 'parties'. Type the following to see the content.
db.parties.find().pretty()
Study the data to make sure all property names are identical. If you created a property call 'partyName' and your form is looking for 'name', nothing will show up.

broccoli-caching-writer fails with "Cannot read property 'images/.DS_Store' of undefined"

I am fairly new to broccoli and have been trying to write a simple plugin to use with ember.js. I used broccoli-caching-writer in my index.js as described on the github page for broccoli-caching-writer:
var CachingWriter = require('broccoli-caching-writer');
module.exports = CachingWriter.extend({
init: function(inputTrees, options)
{
console.log('Initializing plugin with tree');
console.log(inputTrees);
console.log(options);
this.inputTrees = inputTrees;
},
updateCache: function(srcPaths, destDir) {
console.log('updateCache called with srcPaths and destDir');
console.log(srcPaths);
console.log(destDir);
}
});
I then imported the plugin into my ember app (that uses ember CLI) and configured the following in my .brocfile
var plugin = require('broccoli-my-plugin');
var merge = require('broccoli-merge-trees');
pluginTree = new svgSpriter(['images'], {some: 'options'});
....
....
module.exports = merge([app.toTree(),pluginTree]);
Running the above with ember build command gives the following output (paths edited for privacy reasons):
Build failed.
Cannot read property 'images/.DS_Store' of undefined
TypeError: Cannot read property 'images/.DS_Store' of undefined
at CoreObject.proto.shouldBeIgnored (/node_modules/broccoli-svg-sprite/node_modules/broccoli-caching-writer/index.js:135:33)
at CoreObject.proto.keyForTree (/node_modules/broccoli-svg-sprite/node_modules/broccoli-caching-writer/index.js:277:14)
at CoreObject.<anonymous> (/node_modules/broccoli-caching-writer/index.js:267:21)
at Array.map (native)
at CoreObject.proto.keyForTree (/node_modules/broccoli-caching-writer/index.js:266:24)
at /node_modules/broccoli-caching-writer/index.js:87:20
at lib$rsvp$$internal$$tryCatch (/node_modules/broccoli-svg-sprite/node_modules/broccoli-caching-writer/node_modules/rsvp/dist/rsvp.js:489:16)
at lib$rsvp$$internal$$invokeCallback (/node_modules/broccoli-svg-sprite/node_modules/broccoli-caching-writer/node_modules/rsvp/dist/rsvp.js:501:17)
at lib$rsvp$$internal$$publish (/node_modules/broccoli-svg-sprite/node_modules/broccoli-caching-writer/node_modules/rsvp/dist/rsvp.js:472:11)
at lib$rsvp$asap$$flush (/node_modules/broccoli-caching-writer/node_modules/rsvp/dist/rsvp.js:1290:9)
It seems like the plugin is trying to check whether to ignore the path or not, but the options passed to caching writer does not have filterfromcache option defined, so the above should work? Not sure if I'm missing something?
Any help would be appreciated.
Okay, I think the example for overriding the init method needs a little update for newbies like me.
It turns out that the init method in the parent module wasn't being called. Adding the following to my init method fixed it:
CachingWriter.prototype.init.call(this, inputTrees, options);
Not sure if there is a better way though.