How to use commonJS node module in AMD project? - node.js

We are using AMD modules in our project. I want to use a 3rd party commonJS module that is installed through npm install. I had a problem which shim. Hence trying another strategy to use commonJS module in my requireJS build.
So, I am trying to use instructions mentioned here to declare my commonJS module in my AMD build. Here I am facing a different problem. Although I see the r.js is able to load node module in gulp process, its not able to load node module when exceuting
// NOT WORKING. WHY ??
requirejs.optimize(config, function(buildResponse){
console.log('build response', buildResponse);
}, cb);
Here is my full gulp file :
var gulp = require('gulp');
var requirejs = require('requirejs');
config = {
name: 'src/app',
baseUrl: ".",
out: 'dist/app.build.js',
nodeRequire: require,
paths: {
"jquery": "lib/jquery-1.12.0",
"underscore": "lib/underscore"
}
};
requirejs.config(config);
gulp.task('requirejs', function (cb) {
// WORKING: r.js is able to load dagre-d3 in commonJS path
console.log('1.5 dagreD3: ' + requirejs('dagre-d3'));
// WORKING: r.js is able to load dagre-d3 in commonJS path
requirejs(['dagre-d3'], function ( dagreD3 ) {
console.log('2 dagreD3: ' + dagreD3);
});
// NOT WORKING. WHY ??
requirejs.optimize(config, function(buildResponse){
console.log('build response', buildResponse);
}, cb);
});
// The default task (called when you run `gulp` from cli)
gulp.task('default', ['requirejs']);
Here is my git repo illustrating the problem.
Following is the error iam getting while executing gulp:
[11:30:55] Starting 'requirejs'...
1.5 dagreD3: [object Object]
[11:30:55] 'requirejs' errored after 339 ms
[11:30:55] Error: Error: ENOENT: no such file or directory, open '/Users/akandregula/arun/amd-practice/using_commonJS_module_with_amd/dagre-d3.js'
In module tree:
src/app
at Error (native)
at /Users/akandregula/arun/amd-practice/using_commonJS_module_with_amd/node_modules/requirejs/bin/r.js:25150:19
at /Users/akandregula/arun/amd-practice/using_commonJS_module_with_amd/node_modules/requirejs/bin/r.js:3056:39
at /Users/akandregula/arun/amd-practice/using_commonJS_module_with_amd/node_modules/requirejs/bin/r.js:2996:25
at Function.prim.nextTick (/Users/akandregula/arun/amd-practice/using_commonJS_module_with_amd/node_modules/requirejs/bin/r.js:24901:9)
at Object.p.errback (/Users/akandregula/arun/amd-practice/using_commonJS_module_with_amd/node_modules/requirejs/bin/r.js:2995:26)
at Object.p.callback (/Users/akandregula/arun/amd-practice/using_commonJS_module_with_amd/node_modules/requirejs/bin/r.js:2981:23)
at Object.p.promise.then (/Users/akandregula/arun/amd-practice/using_commonJS_module_with_amd/node_modules/requirejs/bin/r.js:3035:23)
at build (/Users/akandregula/arun/amd-practice/using_commonJS_module_with_amd/node_modules/requirejs/bin/r.js:25107:12)
at runBuild (/Users/akandregula/arun/amd-practice/using_commonJS_module_with_amd/node_modules/requirejs/bin/r.js:27115:17)
at Object.context.execCb (/Users/akandregula/arun/amd-practice/using_commonJS_module_with_amd/node_modules/requirejs/bin/r.js:1943:33)
2 dagreD3: [object Object]

Related

gulp can't find module source-map

I'm having an issue with sourcemaps in gulp: when I try to implement gulp-sourcemaps directly through a pipe, but also when I try to feed it in via webpack, which if I've understood correctly, has sourcemaps by default, I keep getting the same confusing error:
Error: Cannot find module 'source-map'
I can see the #gulp-sourcemaps folder in my node_modules, which contains within it an identity-map folder containing a bunch more node_modules including the source-map module in question, so I think everything is hooked up as it should be. That being said, I'm new to gulp, so I might be missing something really obvious.
Can anyone offer me some guidance on how to help gulp find the module?
// package vars
const pkg = require("./package.json");
// gulp
const gulp = require("gulp");
const gulpIf = require("gulp-if");
// webpack
const webpack_config = require("./webpack.config");
// load all plugins in "devDependencies" into the variable $
const $ = require("gulp-load-plugins")({
pattern: ["*"],
scope: ["devDependencies"]
});
// ...
gulp.task("sass", function() {
return gulp
.src(pkg.paths.app.scss + "**/*.scss")
.pipe($.sourcemaps.init())
.pipe($.sass())
.pipe($.autoprefixer())
.pipe($.sourcemaps.write("./maps"))
.pipe(gulp.dest(pkg.paths.app.css))
.pipe(
$.browserSync.reload({
stream: true
})
);
});
// ...
gulp.task("webpack", function() {
return gulp
.src(pkg.paths.app.js + "**/*.js")
.pipe($.webpack(webpack_config))
.pipe(gulp.dest(pkg.paths.public.js));
});
// ...

Accessing filesystem in Angular 2 app using Electron

I know that Angular 2 is run on a web browser, which does not have access to the file system.
However, I'm using Electron as my front-end, and also running the app via electron:
"build-electron": "ng build --base-href . && cp src/electron/* dist",
"electron": "npm run build-electron && electron dist"
Therefore, I run it with npm run electron which at the very end runs electron dist.
Since I'm running through electron and not ng I would think that I should be able to access the filesystem. However, when I do:
import * as fs from 'fs'
I get an error:
ng:///AppModule/AppComponent_Host.ngfactory.js:5 ERROR TypeError: __WEBPACK_IMPORTED_MODULE_0_fs__.readFileSync is not a function(…)
Similarly, when I try: var fs = require('fs');
I get:
ng:///AppModule/AppComponent_Host.ngfactory.js:5 ERROR TypeError: fs.readFileSync is not a function
This is the call resulting in the error:
this.config = ini.parse(fs.readFileSync('../../CONFIG.ini', 'utf-8'))
Does anyone have any idea what's causing this?
Thanks.
Solved it by:
1) Eject webpack: ng eject
2) Add target: 'electron-renderer' to the module.exports array inside webpack.config.js
3) Require remote, since we're in the renderer, but fs is only available in the main process (Read more): var remote = require('electron').remote;
4) Require fs (this time using remotes implementation of require): var fs = remote.require('fs');
And now it works!
I am using
Angular CLI: 7.0.7
Node: 8.12.0
OS: win32 x64
Angular: 7.0.4
I tried the ng eject method it didn't work in my case, it is disabled by default and will be removed completely in Angular 8.0
Error message: The 'eject' command has been disabled and will be removed completely in 8.0.
It worked for me by creating a file called native.js in the src folder and insert the following:
`window.fs = require('fs');
Add this file to the angular-cli.json scripts array:
"scripts": [
"native.js"
]
Add the following lines to polyfills.ts:
`declare global {
interface Window {
fs: any;
}
}`
After that you can access the filesystem with:
`window.fs.writeFileSync('sample.txt', 'my data');`
credits
As I understand it, you build the application with Webpack.
You can expose all Node modules via the externals array in your webpack config.
module.exports = {
"externals": {
"electron": "require('electron')",
"child_process": "require('child_process')",
"fs": "require('fs')",
"path": "require('path')",
...
}
}
Since they are provided through the Webpack externals, one does not have to require them but use them with imports.
import * as fs from 'fs'
You can read more about this problem in my article.
I'm late to the party but I also stumbled upon this problem recently. To the late comers, you can use ngx-fs
https://github.com/Inoverse/ngx-fs
Usage:
const fs = this._fsService.fs as any;
fs.readdir("\\", function (err, items) {
if (err) {
return;
}
for (let i = 0; i < items.length; i++) {
console.log(items[i]);
}
});
I had the same problem and could solve it in an easier way:
Just download this project as start, the 'require'-s are already in the webpack.config.js file (along with the integration of angular, electron and so on):
https://github.com/maximegris/angular-electron
import 'fs' into home.ts (or into any other component) as mentioned by #Matthias Sommer above:
import * as fs from 'fs'
Use 'fs' :)

Optimize multiple requirejs config file

I have a problem with optimization with r.js
I have a project that have multiple requirejs config file
+ app
- module1
* main.js
* foo.js
* bar.js
- main.js
+ build.js
that each main.js has self packages
main.js code is:
requirejs.config({
'baseUrl': '../app/',
'paths': {
'module1' : 'module1/main'
}
});
define(['module1'],function(){});
module1/main.js code like:
requirejs.config({
'paths': {
'foo' : 'module1/foo',
'bar' : 'module1/bar'
}
});
define(['foo','bar'],function(){});
and build.js file is like:
({
mainConfigFile: 'app/main.js',
baseUrl: 'app',
name: 'main',
out: 'dist/main.js',
})
when I execute $ r.js -o build.js it return an error
Tracing dependencies for: main
Error: ENOENT: no such file or directory, open 'D:\Project\Test\app\foo.js'
In module tree:
main
module1
Error: Error: ENOENT: no such file or directory, open 'D:\Project\Test\app\foo.js'
In module tree:
main
module1
at Error (native)
To my knowledge, r.js is simply not able to process multiple requirejs.config calls when it builds a bundle. I've never seen any documentation or issue report, or working example that contradicts this. (RequireJS will let you call requirejs.config multiple times, and combine the configurations passed at run time but this is not the same as having r.js process multiple calls to requirejs.config.
You'll have to combine all your calls to requirejs.config into a single call that you point r.js to with mainConfigFile.
I've recreated your setup on my machine and got the same error you did. If I modify the config in app/main.js to the following, then I can build the bundle:
requirejs.config({
'baseUrl': '../app/',
'paths': {
'module1' : 'module1/main',
'foo' : 'module1/foo',
'bar' : 'module1/bar'
}
});
Just for kicks, I've also tried the following which does not work:
requirejs.config({
'baseUrl': '../app/',
'paths': {
'module1' : 'module1/main'
}
});
requirejs.config({
'paths': {
'foo' : 'module1/foo',
'bar' : 'module1/bar'
}
});
(Note also that baseUrl in the above could be simplified to . rather than ../app/.)

PhantomJS throws error (rasterize.js)

I am trying phantomjs in MEAN stack for report generation but after installing phantom binaries in my ubuntu os server and using phantom node_module + rasterize.js throws below error.
Error: Cannot find module 'events'
phantomjs://bootstrap.js:254 in require
/home/kb/code/backend/backend/api_server/node_modules/phantom/node_modules/dnode/node_modules/dnode-protocol/index.js:1
/home/kb/code/backend/backend/api_server/node_modules/phantom/node_modules/dnode/node_modules/dnode-protocol/index.js:126
Error: Cannot find module 'stream'
phantomjs://bootstrap.js:289
phantomjs://bootstrap.js:254 in require
/home/kb/code/backend/backend/api_server/node_modules/phantom/node_modules/dnode/lib/dnode.js:2
/home/kb/code/backend/backend/api_server/node_modules/phantom/node_modules/dnode/lib/dnode.js:154
Error: Cannot find module 'net'
phantomjs://bootstrap.js:289
phantomjs://bootstrap.js:254 in require
/home/kb/code/backend/backend/api_server/node_modules/phantom/node_modules/dnode/index.js:3
/home/kb/code/backend/backend/api_server/node_modules/phantom/node_modules/dnode/index.js:138
Error: Cannot find module 'http'
phantomjs://bootstrap.js:289
phantomjs://bootstrap.js:254 in require
/home/kb/code/backend/backend/api_server/node_modules/phantom/phantom.js:8
/home/kb/code/backend/backend/api_server/node_modules/phantom/phantom.js:193
/home/kb/code/backend/backend/api_server/node_modules/phantom/phantom.js:194
TypeError: 'undefined' is not a function (evaluating 'phantom.createWebPage()')
:/modules/webpage.js:905
report.js:7
This is my test code.
var phantom = require('phantom');
phantom.create(function (ph) {
ph.createPage(function (page) {
page.open("http://www.google.com", function (status) {
console.log("opened google? ", status);
page.evaluate(function () { return document.title; }, function (result) {
console.log('Page title is ' + result);
ph.exit();
});
});
});
});
Try run command:
npm install -g events stream net http
However, I think that you did wrong way to setup a Node Project. For example, If you want to create a project requires PhantomJS. You should do the steps below:
# create project directory
mkdir myproject
cd myproject
# install phantomjs for your project
npm install --save phantomjs
# create your project file

Durandal optimization with Gulp and Gulp-Durandal not working

We are building an application with Durandal which is quite big at the moment and we currently looking into bundling all JS files located in the App folder into a main-built.js file. Pretty basic and usual stuff I guess.
I'm using Gulp with the Gulp-Durandal extension. Here our gulpfile :
var gulp = require('gulp');
var durandal = require('gulp-durandal');
gulp.task('build-portal', function () {
durandal({
baseDir: 'app',
main: 'main.js',
output: 'main-built.js',
almond: false,
minify: false
}).pipe(gulp.dest('app'));
});
And here's a snippet of our main.js file
require.config({
paths: {
'text': '../Scripts/text',
'durandal': '../Scripts/durandal',
'plugins': '../Scripts/durandal/plugins',
'transitions': '../Scripts/durandal/transitions'
},
shim: {
},
waitSeconds: 0
});
define('jquery', [], function () { return jQuery; });
define('knockout', [], function () { return ko; });
define('ga', function () { return ga; });
define(
["require", "exports", "durandal/app", "durandal/viewLocator", "durandal/system", "plugins/router", "services/logger", "modules/knockout.extensions", "modules/knockout.validation.custom"],
function (require, exports, __app__, __viewLocator__, __system__, __router__, __logger__, __koExtensions__, __koValidationCustom__) {
var app = __app__;
var viewLocator = __viewLocator__;
var system = __system__;
var router = __router__;
As you can see in the gulpfile, we do not want to use Almond but RequireJs instead, for some reasons almond isn't workin with our project and anyhow, we prefer RequireJs whether its bigger than almond at the end. That's where it look to brake. Running the command to build the main-built.js file took sometime but at the end I get the file built with everything in it.
The problem is that when I try to load the application, it is stuck to the loading screen. It doesn't go any further and there's no errors at all in the browser console.
I created a new project on the side to test if our code was somewhat faulty and found that it might not. You can found that project here :
https://github.com/maroy1986/DurandalGulpBundling
If I build that project with almond option to true, everything works fine but if I switch almound off to tell gulp to use RequireJs, I got the same behavior as our app. You got stuck at the loading screen, without any errors.
So here I am, I do read a lot on the subject but didn't found anything to solve this. Hope someone here already encounter these behavior and have a solution to share.
Thanks!
I had the same requirement and issue. It seems require.js wasn't calling the main module which will startup the Durandal app, that's why it's stuck in the loading screen. I was able to resolve it by implicitly calling the main module:
gulp.task("durandal", function() {
return durandal({
baseDir: "app",
main: "main.js",
output: "main-built.js",
almond: false,
minify: true,
rjsConfigAdapter: function(config) {
//Tell requirejs to load the "main" module
config.insertRequire = ["main"];
return config;
}
})
.pipe(gulp.dest("dist"));
});
I downloaded your project and tried building it with the latest versions of gulp and durandal. Initially it didn't build and gave me the following error:
TypeError: Cannot read property 'normalize' of undefined
This is a problem with the text-plugin of rjs and you can solve this by adding the following to your gulp-file (next to the almond, minify, output... properties):
rjsConfigAdapter : function(rjsConfig){
rjsConfig.deps = ['text'];
return rjsConfig;
}
Once I did that, the build finished and I could build with or without minify, almond and require and the application works fine.

Resources