Load external requirejs module into own application - requirejs

I have a large requirejs App. Now I have an external library that comes as a bunch of requireJs modules. My first idea was to compile the modules into a single file an require only this module. But this seems not to work. The compiled module looks like this
lib.js
define("a", function(){
})
define("b", function(){
})
define("", function(){
})
in my module I load it like this
define(['lib'], function(){
})

Related

'require' is not available to index.html running on node.js

I have a server application which uses this to display the home page
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "/index.html"));
});
and my js file in the index.html has these lines in the head
<script src="/public/js/controller.js" type="module"></script>
<script src="/public/js/main.js" type="module"></script>
the main.js is for the frontend js while the controller is for the backed and it imports model.js and model.js use fs using this line
const fs = require("fs");
but when I try to load the index.html using the node server http://localhost:3000 I get this error
model.js:2 Uncaught ReferenceError: require is not defined
at model.js:2
so I added the require.js library and then used it like this
<script src="/public/js/require.js" ></script>
And then I still get this error
require.js:108 Uncaught Error: Module name "fs" has not been loaded yet for context: _. Use require([])
https://requirejs.org/docs/errors.html#notloaded
at makeError (require.js:108)
at Object.s [as require] (require.js:947)
at requirejs (require.js:134)
at model.js:2
Can someone please advise, what should one do to make this work? I am stuck for more than 2 days on this and I am pretty new to node.js and this 'require' thing.. but I know it's a very important part of node.js.
So I would like to have some clarity and some advise/help on what an html page that's not using a bundler and running directly from a node server have to do to handle this..
and just so that I am clear about what I mean by 'this' all I am trying to do is get a list of folder names that I want use as navigation menu (li items) on the front-end.. I am using this command on node.js to do get the array..
fs.readdir('./data/')
I need to have this array in my index.html which is on the same server/folder/application that is running on node.js..
I assumed that if node.js is displaying an html file (with app.get) I would be able to use the fs command this way.. am I wrong? If so, what do I have to do to use readdir and get the array to display as menu on the front-end?
The "fs" module is a built-in module in NodeJS to allow you to work with the filesystem. It isn't available on the client-side (imagine people can access your webpage and manipulate your filesystem!!).
What you're trying to do is get a list of folder names that you want use as navigation menu (li items) on the front-end. For that, you can get the list of folder names on the server-side using "fs" module, then using template engine to render HTML file with the data.
For NodeJS, there are some popular template engines: EJS, pug, nunjucks....
You might have your server.js as a ES6 module, which is a good thing as it took me an hour to set it up like that myself.
You can do import * as fs from 'fs'; or import {fs} from 'fs'; but I did import { promises as fs } from "fs"; because I like my fs calls async.
Gives it a python feel.

Controller reference is not defined node.js application

I'm working on a node.js single-page web application where I wanna use MVC. On my back-end, i'm using postgres database to store data that will be provided by the user throught forms interaction. For this, i'm also using Sequelize.
When 'npm start' runs, the application verifies if the database already exists locally, if not, then it is created with its tables and relations, just as expected.
On my front-end, the application loads a file called index.html (where all forms will be located). In this file, I'm trying to use my controllers to call 'create' methods using Sequelize, but i can't exacly call those functions on html script tag.
The first errors i was getting was 'required is not defined' when I was trying to do things like 'var PropController = require('../controllers/PropriedadeController.js')'. After some research, just figured out that it has somethings to do with browser/client-side in JavaScript.
I'm now trying to deal with this using Browserify, but still can't find out how it fits in my case. I did some research, but couldn't find a similar situation.
Basically, my idea is to reference all my controllers in a script.js file, and then browserify this file, in order to use it in my html file in the script tag.
My controller file:
const models = require("../models")
exports.findCreate = obj => {
return new Promise((resolve, reject) => {
models.Produtores.findOrCreate({
attributes: ["propt_nomeProdutor"],
where: { propt_nomeProdutor: obj.propt_nomeProdutor },
defaults: {
propt_nomeProdutor: obj.propt_nomeProdutor
}
})
.then(resp => {
resolve(resp);
})
.catch(e => {
reject(e);
});
});
};
My script.js file:
const ProdController = require("./ProdutorController");
module.exports = ProdController
And in my index.html file, after running 'browserify script.js -o bundle.js', i'm calling this generated script. So now, Inside a script tag, i'm trying to:
`(html form here)
<script src="../controllers/bundle.js"></script>
</body>
</html>
<script>
// ProdController.findCreate(obj) ...
</script>`
After trying this, i'm getting an error 'ProdController is not defined'. I even tried to browserify my controller file and my script.js into the bundle.js file, but then i'm getting an error witch I couldn't solve either:
Uncaught Error: Cannot find module './dialects/postgres/data-types'
I would like to know if there is any solution for this. I'm afraid that it's not possible to do this using these dependencies all together. I did a similar application using Electron, but now i'm trying to deal with a browser, and can't figure out how to do it.
This project is in my github repo: https://github.com/gabrielftwgarcia/TCC2
Any help will be greatly appreciated.
I think you are not familiar with front-end and back-end concepts. Controller is used at back-end side and it cannot use at front-end side. If you want to call a controller method you should write a new router to execute that method.
And another important thing is require method belongs to Node scripts and cannot be used at front-side.

Re-requiring module that parent requires

I'm in the process of learning NodeJS (using Express), and came across something that struck me as odd.
In app.js i'm requiring a module (passport in this case), and then requiring a second module (passport-strats.js) which I developed. Inside of passports-strats I have to re-require passport even though it's already required in app.js.
This isn't the only example, I have some modules required in three files that are all tightly related. Is this standard or am I missing some crucial piece of structuring NodeJS applications?
For you require the passport module once you should require it in passport-strats.js and export it from this module. In app.js you can use both modules just importing passport-strats.js. ie:
//passport-strats.js
var {passport} = require("./path");
//other code
module.exports = { passport, someVariableFromCurrentModel };
//In app.js
var {passport, someVariableFromCurrentModel} = require("./passport-strats");

I want load minify js file by RequieJs

We want to load module using RequireJs.
By the way, the test server should load 'tab.js',
and the real server should load 'tab.min.js'.
We use RequireJS in the Multiple Page Application.
We are using it like "require('tab', function () { ... });" in html files.
So it is difficult to change the name of the loaded module.
// test server
require('tab', function (Tab){ ... } // => load tab.js
// real server
require('tab', function (Tab){ ... } // => load tab.min.js
Is there any way to make this possible?
Use two RequireJS configurations:
For the test server, set the configuration so that tab.js is loaded. How you'd do this depends on specifics you don't provide in your question. A generic way to do it would be to have a paths setting like:
paths: {
tab: "path/to/tab",
}
Remember not to put the .js extension in the path you provide.
For the production server (i.e. the "real" server), set the configuration so that tab.min.js is loaded. The example above would be modified to:
paths: {
tab: "path/to/tab.min",
}

Using Vue JS with Require JS?

I installed the following via Bower:
jQuery 3.1.0
Vue 1.0.26
Require.js 2.2.0
But when I load my site, "Vue" is undefined.
I tried var vue = require('Vue') and stuff, but it doesn't seem to work.
Vue says it is a AMD module and so is Require.js... What am I missing?
var vue = require('Vue') won't work by itself. Either you:
Change it to the form of require that takes a callback:
require(['Vue'], function (vue) {
// code that uses Vue
});
Or put your require call in a define call:
define(function (require) {
var vue = require('Vue');
});
As Linus Borg pointed out, require with a single string is CommonJS syntax, which RequireJS supports only if it appears in the callbacks passed to define. (See this.)

Resources