configuring requirejs reading from node_modules - javascript

I'm trying to setup a nodejs project to use requirejs. I call my program with node r.js ./config/main.js and my main.js looks like the following:
var cs = require("coffee-script");
var requirejs = require("requirejs");
requirejs.config({
nodeRequire: require,
baseUrl: ".",
paths: {
cs: "cs",
CoffeeScript: "CoffeeScript",
csBuild: "csBuild",
express: "express",
nohm: "nohm",
redback: "redback",
_: "underscore",
"connect-redis": "connect-redis",
freebase: "freebase"
}
});
console.log("hetet");
requirejs(["cs!./config/app"], function(app){
console.log("closing")
});
and inside app.coffee:
define((require) ->
express = require("express")
RedisStore = require("connect-redis")(express)
app = express.createServer()
config = require('cs!./config')
require('cs!./setup')(app, express, RedisStore)
require('cs!./routes')(app)
require('cs!../src/server')
app.listen(config.server.port)
)
I seem to fail in main.js with the error:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Calling node's require("config") failed with error: Error: Calling node's require("config") failed with error: Error: Cannot find module 'config'
and What I have noticed is when I comment out the line var requirejs = require("requirejs"); (in main.js), I get further and fail at the line RedisStore = require("connect-redis")(express) (in app.coffee) with the error:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: undefined is not a function
at ./config/app.coffee:10:41
I have been having a lot of trouble configuring requirejs in node any help would be appreciated.
thanks

It is best to not configure requirejs to look in node_modules, since modules in that area are modules formatted for node. There is a little bit more info in the requirejs node page.

Related

trying to run npm package (readability) from browser using Browserify with no success

so i'm trying to make readabilityJs available to me from the browser.
i want to use it later in my app, i'm using BrowserifyJS + beefyJS to make it work.
here i'm trying to expose the function i want to use:
var read = require("readability-js");
module.exports = (url) => read(url, (err, article, meta) => {
// Main Article
console.log(article.content.text());
//
// Title
console.log(article.title);
// Article HTML Source Code
console.log(article.content.html());
});
than i using the function in index.js
var readability = require("./Readability");
const url = "https://tim.blog/2019/10/31/edward-norton-motherless-brooklyn/";
readability(url);
after that i'm running browserify to make bundle.js and beefy to run it all
browserify index.js -o bundle.js
beefy index.js 8080
here is what i getting:
bundle.js:35798 Uncaught TypeError: Cannot read property 'content' of undefined
at bundle.js:35798
at bundle.js:62995
at Request._callback (bundle.js:62933)
at self.callback (bundle.js:63402)
at emitOne (bundle.js:16927)
at Request.emit (bundle.js:17005)
at Request.self._buildRequest (bundle.js:63634)
at Request.init (bundle.js:63812)
at new Request (bundle.js:63378)
at request (bundle.js:63059)
can you help me implement it right?

Gulp location of unhandled error in events.js:141

When I run task for example using comman gulp scripts:common, I get this output:
[14:05:47] Requiring external module babel-core/register
[14:05:49] Using gulpfile /home/sites/blablabla/gulpfile.babel.js
[14:05:49] Starting 'scripts:common'...
events.js:141
throw er; // Unhandled 'error' event
^
SyntaxError: Unexpected token
Well, for SyntaxError it would be useful to know where it found that unexpected token. How to tell it to show at least file and line? Where to find that evetns.js file? Could I put console.trace() or something like that there?
I solve this problem by running jshint on my scripts:
/*
* `gulp check_scripts` - Lints script files
*/
gulp.task('check_scripts', function() {
return gulp.src([
'gulpfile.js' //, other scripts to check
])
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});
enabled.failJSHint is there to allow errors to pass in local environment but fail in production.
This will lint any syntax errors in your scripts.
Additionally you may want to hook it to other task so it's run automatically before proper build:
gulp.task('default', ['check_scripts', 'clean'], function() {
gulp.start('build');
});
This is the general idea.
You can look at error stack trace by adding custom "on error" handler to the gulp task.
gulp.task('compile:js', function() {
return (
gulp.src(jsPath)
.pipe(yourCustomTask())
.on('error', function(err) {
console.log(err.stack);
this.end();
})
);
});
Also, as another variant, adding gulp-plumber into pipeline makes error messages more clear.

Typescript module, require external node_modules

I need to use a simple node_module inside a simple typescript file, but it seems that the compiler doesn't want to get it.
Here's my simple ts file :
import glob = require('glob');
console.log(glob);
And I've got this error :
[13:51:11] Compiling TypeScript files using tsc version 1.5.0
[13:51:12] [tsc] > F:/SkeletonProject/boot/ts/Boot.ts(4,23): error TS2307: Cannot find external module 'glob'.
[13:51:12] Failed to compile TypeScript: Error: tsc command has exited with code:2
events.js:72
throw er; // Unhandled 'error' event
^
Error: Failed to compile: tsc command has exited with code:2
npm ERR! skeleton-typescript-name#0.0.1 start: `node compile && node ./boot/js/Boot.js`
npm ERR! Exit status 8
npm ERR!
npm ERR! Failed at the skeleton-typescript-name#0.0.1 start script.
However, when I use a simple declaration in this same script, it works :
var x = 0;
console.log(x); // prints 0 after typescript compilation
What am I doing wrong in this case ?
EDIT:
Here's my gulp file :
var gulp = require('gulp');
var typescript = require('gulp-tsc');
gulp.task('compileApp', ['compileBoot'], function () {
return gulp.src(['app/src/**/*.ts'])
.pipe(typescript())
.pipe(gulp.dest('app/dist/'))
});
gulp.task('compileBoot', function () {
return gulp.src(['boot/ts/*.ts'])
.pipe(typescript({
module:'commonjs'
}))
.pipe(gulp.dest('boot/js/'))
});
gulp.start('compileApp');
Thanks for advance
Thanks for advance
You are using the correct syntax:
import glob = require('glob');
But the error: Cannot find external module 'glob' is pointing out that you are using a special case.
By default, the compiler is looking for glob.ts, but in your case you are using a node module, not a module that you have written. For this reason, the glob module will need special treatment...
If glob is a plain JavaScript module, you can add a file named glob.d.ts with type information that described the module.
glob.d.ts
declare module "glob" {
export class Example {
doIt(): string;
}
}
app.ts
import glob = require('glob');
var x = new glob.Example();
Some Node modules already include the .d.ts in the package, in other cases you can grab it from Definitely Typed.
Here is the error with your code
import glob = require('glob');
Because in node.js import is not a reserved keyword. If you require any module in your application, you simply require it using the statement
var glob = require('glob');
Once done you can then use
console.log(glob);
To print the value of glob.Replacing import will hopefully do the job for you.

gulp-uncss 'TypeError' undefined when used with gulp-if

I started loving gulp but I've been having too many cryptic errors that are very hard to find and at the end I'm working for my gulpfile.js instead of doing my job.
Anyway, I tried gulp-uncss before, outside gulp-useref and therefore outside gulp-if, but my gulpfile.js ended up too bulky and unreadable. Now it's readable but it doesn't work. Hurray.
var p = require('gulp-load-plugins')();
gulp.task('html', function () {
var assets = p.useref.assets();
gulp.src('*.html')
.pipe(assets)
.pipe(p.if('*.js', p.uglify()))
.pipe(p.if('*.css', p.uncss()))
.pipe(assets.restore())
.pipe(p.useref())
.pipe(gulp.dest(build_folder))
.pipe(p.size());
});
That generates this:
[12:47:53] /long/path/web $ gulp html
[12:48:06] Using gulpfile /long/path/web/gulpfile.js
[12:48:06] Starting 'html'...
[12:48:07] 'html' errored after 507 ms
[12:48:07] TypeError: Cannot set property 'ignoreSheets' of undefined
at Object.module.exports (/long/path/web/node_modules/gulp-uncss/index.js:14:26)
at Gulp.<anonymous> (/long/path/web/gulpfile.js:45:31)
at module.exports (/long/path/web/node_modules/gulp/node_modules/orchestrator/lib/runTask.js:34:7)
at Gulp.Orchestrator._runTask (/long/path/web/node_modules/gulp/node_modules/orchestrator/index.js:273:3)
at Gulp.Orchestrator._runStep (/long/path/web/node_modules/gulp/node_modules/orchestrator/index.js:214:10)
at Gulp.Orchestrator.start (/long/path/web/node_modules/gulp/node_modules/orchestrator/index.js:134:8)
at /usr/local/lib/node_modules/gulp/bin/gulp.js:129:20
at process._tickCallback (node.js:355:11)
at Function.Module.runMain (module.js:503:11)
at startup (node.js:129:16)
at node.js:814:3
[12:48:12] /long/path/web $
Uncss was crucial to my workflow and I can't crack what's going wrong here. Any clue?
EDIT: This is what's in /long/path/web/node_modules/gulp-uncss/index.js until line 14
'use strict';
var uncss = require('uncss'),
gutil = require('gulp-util'),
assign = require('object-assign'),
transform = require('stream').Transform,
PLUGIN_NAME = 'gulp-uncss';
module.exports = function(options) {
var stream = new transform({ objectMode: true });
// Ignore stylesheets in the HTML files; only use those from the stream
options.ignoreSheets = [/\s*/];
Well, your excerpt of gulp-uncss/index.js states, that it can not handle an undefined options parameter - which it is not in you gulpfile:
.pipe(p.if('*.css',
p.uncss({
html: [ '*.html' ] // html files to check for styles to keep
})
))
The doc also states, that html is an required option attribute: npmjs.com/package/gulp-uncss#html
Type: Array|String Required value.
An array which can contain an array of files relative to your gulpfile.js, and which can also contain URLs. Note that if you are to pass URLs here, then the task will take much longer to complete. If you want to pass some HTML directly into the task instead, you can specify it here as a string.

Use glob matching, when passing files to browserify in gulp

All the examples I have seen using browserify and gulp assume that you only want to browserify 1 file. This is usually not the case.
I came across an example that used vinyl-transforms, but I am unable to get it to work correctly. Here is the (coffee-script) code:
# Browserify JS
gulp.task 'browserify', [], ->
# Create the transform
br = transform (f) ->
return browserify(f).bundle()
# Run browserify
gulp.src(['./public/js/**/*.js'])
.pipe(br)
.pipe(gulp.dest('.'))
But I get the following error:
[10:50:55] Starting 'browserify'...
events.js:72
throw er; // Unhandled 'error' event
^
Error: write after end
The easiest way would be to use glob directly:
var glob = require('glob');
gulp.task('browserify', function() {
var files = glob.sync('./public/js/**/*.js');
return browserify({entries: files})
.bundle()
.pipe(gulp.dest('.'));
});

Categories

Resources