Using Vue JS with Require JS? - requirejs

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.)

Related

Prevent webpack from removing crypto in nodejs API

I have a node-js API that's part of an nx workspace and I'm trying to use the core crypto node-js module, however I think it's getting stripped out by webpack.
My code uses the following:
crypto.getRandomValues(new Uint32Array(1))[0].toString(16)
However I get a runtime error:
ReferenceError: crypto is not defined
Am I right in thinking this issue is likely being caused by webpack? And if so, how can I use crypto in my API?
I'm very new to webpack, so I'm pretty clueless here. My nx project uses the #nrwl/node:webpack executor (the default for node-js APIs), and I've followed the steps here on how to customize this projects webpack configuration, so my custom webpack config is being used, I just dont know what to do with it on order to allow my API to use crypto.
Any help on this would be appreciated.
For completeness, here's what my custom webpack config looks like, but it makes no difference to the problem. Note that his was crafted based on some of the suggested answers here:
const { merge } = require('webpack-merge');
/** #type { import('webpack').Configuration } */
const webpackConfig = {
target: 'node',
resolve: {
fallback: {
"crypto": false
}
}
};
module.exports = (config, context) => merge(config, webpackConfig);
Edit: As a workaround, I've imported the randomUUID function from crypto and can use this to do what I need to do. It seems having this import means crypto gets included in the webpack.
import { randomUUID } from 'crypto';
randomUUID().split('-')[0];
In your above code + runtime error, it seems like you haven't imported crypto correctly.
Furthermore you are mixing up some concepts. Webpack is normally used for frontend projects, as Node.js supports requiring modules out of the box and you don't need to compile your code, as you don't need to generate a javascript bundle that's servable by browsers.
Because your project runs in the browser, but your tests run in Node, which has a different global namespace, you get issues. In the browser crypto is defined globally, but in Node you need to import the crypto standard library, the "suggested answers" you are linking to talks about this concept.
To fill in the gap between browser and Node, to ensure the code you write works for test + browser, you use polyfills.
In your usecase you have a Node.js project. Crypto is a standard library for Node.js and you can just require it, why should you configure webpack to create fallbacks for it or use polyfills?

'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.

Can a node module require a vanilla js file?

Trying to fast-forward through my node+npm+webpack learning, and here's a simple boolean question: can a node module js file require a vanilla js file? Or, do I need to "node-ify" the vanilla js with a module.exports?
In some tests, I've seen that a module.exports isn't required to "node-ify" some vanilla js. What is required is a parent folder for the vanilla js that also contains a package.json that specifies a main js entry file. Then, it's npm-installable into other node modules. module.exports is for a module's api.

Webpack-dev-server and isomorphic react-node application

I've managed to properly use webpack dev server alongside with a node server (express), using the plugin section inside webpack's config.
It all works fine but now I'm trying to go isomorphic and use client-side components inside the express application.
So far the only problem I'm encountering is that without webpack 'parsing' my server-side code I get to a situation where I require components but the paths are not solved
I.E.
Inside a component
'use strict';
import React from 'react';
import { RouteHandler, Link } from 'react-router';
import Header from 'components/header/main'; // <-- This line causes the error because webpack is not working when parsing this JSX server-side
export default React.createClass({
displayName: 'App',
render() {
return ( // ... More code
Shall I configure webpack in another way or do I have to change all the imports to be valid server-side?
the codebase is here in case you want to see the actual state https://github.com/vshjxyz/es6-react-flux-node-quickstart
In order to be able to require components in a way such as require('components/Header.js'); and avoid using long relative paths such as require('../../../../../../Header.js'); you can add this code to your node app before any require() calls:
process.env.NODE_PATH = __dirname;
require('module').Module._initPaths();
However, since this relies on a private Node.js core method, this is
also a hack that might stop working on the previous or next version of
node.
Other possible solutions to this problem can be found at https://gist.github.com/branneman/8048520
I see 2 options:
Compile client code with webpack as well. If client's entry
point is in the same dir as server's - it should work with your
present code. This looks natural to me.
Use relative paths i.e.
import Header from './components/header/main'

include angular in jasmine-node

I'm trying to test an angular module using jasmine-node, my test is setup as
var fs = require('fs');
var angular = require('../bower_components/angular/angular')
var fsm = require('../filesystemModel');
describe("get files",function(){
it("should get files from the file system",function(){
console.log(fsm);
});
});
Unfortunately, this fails to load angular, and therefore, the filesystemModel breaks because angular is undefined. I think this is because angular is looking for window and document, which I don't think are provided in jasmine-node.
I know node-webkit talks about using chromedriver for testing, but I'm trying to be consistent with tests for modules, some of which are available outside of node-webkit, some which require node-webkit.
Any suggestions on getting jasmine-node testing with node-webkit? Or node testing with karma is another option.
You can use Karma which runs the tests in real browsers.

Resources