Giter VIP home page Giter VIP logo

gulp-requirejs-optimize's Introduction

gulp-requirejs-optimize

Build Status npm version Coverage Status Dependency Status

Optimize AMD modules in javascript files using the requirejs optimizer.

Install

$ npm install --save-dev gulp-requirejs-optimize

Usage

Simple

var gulp = require('gulp');
var requirejsOptimize = require('gulp-requirejs-optimize');

gulp.task('scripts', function () {
	return gulp.src('src/main.js')
		.pipe(requirejsOptimize())
		.pipe(gulp.dest('dist'));
});

Custom options

gulp-requirejs-optimize accepts almost all of the same options as r.js optimize (see below).

var gulp = require('gulp');
var requirejsOptimize = require('gulp-requirejs-optimize');

gulp.task('scripts', function () {
	return gulp.src('src/main.js')
		.pipe(requirejsOptimize({
			optimize: 'none',
			insertRequire: ['foo/bar/bop'],
		}))
		.pipe(gulp.dest('dist'));
});

Multiple Modules

Each file passed to the plugin is optimized as a separate module.

var gulp = require('gulp');
var requirejsOptimize = require('gulp-requirejs-optimize');

gulp.task('scripts', function () {
	return gulp.src('src/modules/*.js')
		.pipe(requirejsOptimize())
		.pipe(gulp.dest('dist'));
});

Options generating function

Options can also be specified in the form of an options-generating function to generate custom options for each file passed. This can be used to apply custom logic while optimizing multiple bundles or modules in an app.

var gulp = require('gulp');
var requirejsOptimize = require('gulp-requirejs-optimize');

gulp.task('scripts', function () {
	return gulp.src('src/modules/*.js')
		.pipe(requirejsOptimize(function(file) {
			return {
				name: '../vendor/bower/almond/almond',
				optimize: 'none',
				useStrict: true,
				baseUrl: 'path/to/base',
				include: 'subdir/' + file.relative
			};
		}))
		.pipe(gulp.dest('dist'));
});

Sourcemaps support

The plugin supports gulp-sourcemaps only if preserveLicenseComments is set to false, as described in the r.js docs. If preserveLicenseComments is not specified and the gulp-sourcemaps plugin is detected, the plugin will automatically set preserveLicenseComments to false.

var gulp = require('gulp');
var requirejsOptimize = require('gulp-requirejs-optimize');
var sourcemaps = require('gulp-sourcemaps');

gulp.task('scripts', function () {
	return gulp.src('src/main.js')
		.pipe(sourcemaps.init())
		.pipe(requirejsOptimize())
		.pipe(sourcemaps.write())
		.pipe(gulp.dest('dist'));
});

API

requirejsOptimize(options)

options

Options are the same as what is supported by the r.js optimizer except for out, modules, and dir.

The options parameter can be specified as a static object or an options-generating function. Options-generating functions are passed a file object and are expected to generate an options object.

Differences From r.js

out

r.js supports out as a string describing a path or a function which processes the output. Since we need to pass a virtual file as output, we only support the string version of out.

modules and dir

r.js supports an array of modules to optimize multiple modules at once, using the dir parameter for the output directory. The same thing can be accomplished with this plugin by passing the main file of each module as input to the plugin. gulp.dest can be used to specify the output directory.

This means an r.js config file for optimizing multiple modules that looks like this:

{
	"baseUrl": "src/modules",
	"dir": "dist",
	"modules": [{
		"name": "one"
	}, {
		"name": "two"
	}]
}

Would look like this as a gulp task with this plugin:

gulp.task('scripts', function () {
	return gulp.src('src/modules/*.js')
		.pipe(requirejsOptimize())
		.pipe(gulp.dest('dist'));
});

License

MIT © Jonathan Lounsbury

gulp-requirejs-optimize's People

Contributors

jlouns avatar joshdover avatar jridgewell avatar kagami avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

gulp-requirejs-optimize's Issues

Extra sourceMappingURL

Hi,

I tried using gulp-requirejs-optimize with sourcemaps and find that the optimized file contains two lines of sourceMappingURL

//# sourceMappingURL=main.js.build.js.map
//# sourceMappingURL=main-optimized.min.js.map

The first line should not be in the optimized file. Is there a setting that I should use to remove the first line?

Here is the code that I have.

var $ = require('gulp-load-plugins')();
gulp.task('optimize', function () {
        gulp.src('app/scripts/main.js')
            .pipe($.sourcemaps.init())
            .pipe($.requirejsOptimize({
                mainConfigFile: 'app/scripts/main.js',
                out: 'main-optimized.min.js',

            }))
             .pipe($.sourcemaps.write('/'))
            .pipe(gulp.dest('dist/scripts'));

});

Thank you.

Path must be a string.

I can confirm it works with Node v4.6
I got an error on Node v8.2.1

I got success when packaged with r.js directly

config

require.config(
{
    ... ...
    map: {
        '*': {
            'css': 'requirejs/css.min'
        }
    },

    paths: {
        ... ...
        'swiper': 'lib/swiper/swiper-3.4.2.jquery.min',
        ... ...
    },

    shim: {
        'swiper': ['css!./lib/swiper/swiper-3.4.2.min.css']
    }
})

gulpfile.js

... ...
gulp.task('js:main', function () {
    gulp.src('src/js/app.js')
        .pipe(requirejsOptimize({
            mainConfigFile: 'src/js/requirejs/require.config.js'
        }))
        .pipe(rename('main.min.js'))
        .pipe(gulp.dest('dist/js'));
});
... ...

folder: requirejs

    css-builder.js
    css.min.js
    normalize.js
    require.config.js
    require.js
    text.js

error

TypeError: Path must be a string. Received [Function]
In module tree:
    app
      script
        requirejs/css.min


events.js:182
      throw er; // Unhandled 'error' event
      ^
Error: TypeError: Path must be a string. Received [Function]
In module tree:
    app
      script
        requirejs/css.min

    at assertPath (path.js:28:11)

    at f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:28326:19
    at f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:3059:39
    at f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:2999:25
    at Function.prim.nextTick (f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:28077:9)
    at Object.errback (f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:2998:26)
    at Object.callback (f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:2984:23)
    at Object.then (f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:3038:23)
    at build (f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:28283:12)
    at runBuild (f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:30291:17)
    at Object.execCb (f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:1946:33)
    at Module.check (f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:1133:51)
    at Module.<anonymous> (f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:1389:34)
    at f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:384:23
    at f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:1439:21
    at each (f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:309:31)
    at Module.emit (f:\Projects\Template-Gulp\node_modules\requirejs\bin\r.js:1438:17)

css plugin : https://github.com/guybedford/require-css

Are there any ways which could help me locate issues of dependency?

Hi
I am new to gulp and requirejs optimizer.
As the screenshot shown below, this plugin output little information about the path-related issue of my amd module. It feels troublesome to find out which file was not placed at the desired path in my source folder.

gulp-requirejs-optimize-error

I wonder if there is a good practice which could help me locate those issues exists in my source folder?

Will you add support for "out" option?

The RequireJS optimizer may concatenate all input JavaScript files to a single output file. It adds a module name to each of the modules it concatenates in the files. This process cannot be achieved by a Gulp task.

Would you mind adding support for "out" option to gulp-requirejs-optimize?

Background info: I have written a library which I want to offer as a single file. The source code of this library consists of a number of modules, though.

Question on concatenation / r.js behavior

@jlouns when I run the optimizer on my source, it seems to duplicate modules where a reference is desired, and I'm wondering if I'm configuring it wrong?

Here's a simple example:

// in src/app/foo.js
export default class Foo { }
// in src/app/bar.js 
import Foo as './Foo';
export default class Bar extends Foo { }

I run this through babel using the amd plugin and we get something like this:

// in build/app/foo.js
define(['exports'], function (exports) {
  Object.defineProperty(exports, "__esModule", { value: true });

  var Foo = function () { }
  // more stuff here
  exports.default = Foo;
});
// in build/app/bar.js
define(['exports', './Foo'], function (exports, Foo) {
  Object.defineProperty(exports, "__esModule", { value: true });

  var Bar = function () { }
  // more stuff here
  exports.default = Bar;
});

But now when I run this through the optimizer, I get the contents of foo.js embedded in bar.js instead of referenced. So, I end up with a module for Foo defined in foo.js and another one in bar.js.

// in dist/app/bar.js
define(['exports', function (exports) { Object.defineProperty(exports,"__esModule", {value: true}); var Foo=function() { } /* etc */ exports.default=Foo; }); define(['exports', './Foo', function(exports, Foo) { /* etc */ });

If I concat these all together, I get the same module defined all over the place. What am I missing?

How to reduce the Optimizing cost time?

Frist,thanks for your great job.
I used this package on my project, the function is runing well ,but cost too much time on Optimizing progress.
Each file cost 3s or more.

my gulpfile.js code is:

gulp.task('js',function(){
    return gulp.src(jsSrc)
    .pipe(flatmap(function(stream, file){
        var fileInfo=Tools.getFileInfo(file.path),
            fileName=fileInfo.taskName+'.min.js';
        return gulp.src(file.path)
            .pipe(requirejsOptimize(function(file){
               return {
                   optimize: 'none',
                   paths:{
                       jquery: path.join(__dirname,'vendor_bower/jquery/dist/jquery'),
                       header: path.join(__dirname,'src/js/lib/header'),
                       headerDark: path.join(__dirname,'src/js/lib/header-dark'),
                       footer: path.join(__dirname,'src/js/lib/footer'),
                       layout: path.join(__dirname,'src/js/lib/layout'),
                       handlebars: path.join(__dirname,'vendor_bower/handlebars/handlebars'),
                       jBox: path.join(__dirname,'vendor_bower/jbox/Source/jBox'),
                       playlist: path.join(__dirname,'vendor/playlist/js/playlist'),
                       wx: path.join(__dirname,'vendor/justshare/js/jweixin-1.0.0'),
                       justshare: path.join(__dirname,'vendor/justshare/js/justshare'),
                       widget: path.join(__dirname,'src/js/widget'),
                       vendor_bower: path.join(__dirname,'vendor_bower'),
                       vendor: path.join(__dirname,'vendor')
                   },
                   //非规范模块加载方式
                   shim: {
                       'playlist': {
                           deps: ['jquery'],
                           exports: 'playlist'
                       },
                       'justshare': {
                           deps: ['jquery'],
                           exports: 'justshare'
                       },
                       'jBox': {
                           deps: ['jquery'],
                           exports: 'jBox'
                       }
                   }
               }
            }))
            .pipe(uglify())
            .pipe(rename(fileName))
            .pipe(gulp.dest(dest_js))
            .pipe(debug({title: createBonus()+'--------脚本【'+ fileInfo.taskName +'】'}))
    }))
});

Closure Compiler

I did not find any way to use closure compiler. Is there a way to use gulp-closure-compiler?

No errors from r.js optimizer shown?

Is it just me, or is it known that when using this it silently fails without showing any errors from r.js?

This makes debugging a configuration very difficult.

Cannot output when gulp.dest

Hi.
I cannot get the output when using this plugin.
My gulp task is like this:

gulp.task('scripts', function () {
    return gulp.src('pages/web/room.js')
        .pipe(rjs({
            appDir: 'apps',
            baseUrl: 'apps',
            optimize: 'none'
        }))
        .pipe(gulp.dest('dist'));
});

The log is like this:

[11:27:24] Starting 'scripts'...
[11:27:25] Finished 'scripts' after 17 ms

And there is no dist folder created.Can you tell me what‘s the problem?

what does 'src' use for when optimize single module

my build file is like

{
        name: "hermes",
        out: "./dist/hermes.js",
        baseUrl: "./",
        mainConfigFile: "main.js",
        preserveLicenseComments: !1,
        generateSourceMaps: !1,
        optimizeCss: "none",
        writeBuildTxt: !1
 }

as it's use to optimize a module and will generate one file

for(let moduleName in buildConfig){
     gulp.task("rjs:"+moduleName, function () {
        return gulp.src(
                [
                    './empty.js'
                ]
            )
            .pipe(requirejsOptimize(function(file){
                return buildConfig[moduleName]
            }))
            .pipe(gulp.dest("./"));
    });
    taskList.push('rjs:'+moduleName);
}

What does gulp.src use for ? And How can I remove it?
If the file path is null/undefied or no file path , it's broken.
If the path is the whole app , it will scan all file and optimizing all file and waste a lot of time.
So I have to add a empty.js to make it run

Requirejs option baseurl doesn't work as expected

I have a multi-module project and the file structure is like below,

/
|-- build
|    |-- modules
|    |   --- moduleA.js // require([a,b,c,d,e...])
|    |   --- moduleB.js // require([a,b,c,d,e...])
|    |   --- moduleC.js // require([a,b,c,d,e...])
|-- src
|    | --- modules
|        |-- components
|        |    --- a.js
|        |    --- b.js
|        |-- ...
|    | --- vendor
|        | --- d.js
|        | --- e.js
|        | --- f.js

And I try to optimize the above js files like below,

gulp.src( "build/modules/*.js").pipe(requirejsOptimize({
    baseUrl : "src",
    // ....
).pipe(gulp.dest('dist'))

when this task starts there is a log shown as below,

[11:43:10] Optimizing moduleA.js

However, it keeps throwing an error that no such file or directory, open /myfolder/src/moduleA.js .

I am confused about this output. It seems that moduleA.js is found at first step since the above log is printed, but then gulp or this plugin started to look for the file according to baseUrl?
How can I make it work? I have to configure baseUrl since all the js codes are located under src/

Module name and path to module

I'm trying to concat every file in my project into one and name anonymous AMD define with their path. Part of the files aren't AMD modules at all but I need all of them in one big clump.
I have expected this to work :

plugins.requirejsOptimize = require('gulp-requirejs-optimize');
gulp.task('scripts', function () {
    return gulp.src([ 'app/**/*.js'])
        .pipe(plugins.requirejsOptimize())
        .pipe(plugins.concat('some.js'))
        .pipe(gulp.dest('app'));
});

Everything were fine until I've noticed that my define(function(){ turned to be define('foo/bar', [], function(){ which isn't right. I've tried baseUrl parameter and it didn't work at all. It should have been define('app/foo/bar' . But that were alright because I could just change baseUrl to '/app' in my client-side config file.
But next up my app failed to load because not every part of the app is defined as AMD module and obviously they are not arranged in alphabetical order - that caused some errors(previously everything were loading from index.html in right order). OK thought I and used optimization tool in previous version of build that uses gulp-htmlbuild.

And now every file is served one by one to requirejsOptimize with something like this :

gulp.src('app/foo/bar.js')
        .pipe(plugins.requirejsOptimize())

and I've got for a module name just bar. That is unacceptable. I need module name to contain full path to the module starting with working directory as app

So I've tried this :

plugins.requirejsOptimize(function(file){
                        var path = file.base.replace(/.*angular\/(app.*)/, '$1');
                        var name = (path + file.relative).split('.')[0];
                        console.log(name);
                        return {
                            name : name,
                            include : path + file.relative
                        };
                    }

where .*/angular/app/.* will be basically converted to app/foo . That gives next error

ERROR: module path does not exist : .*/angular/app/foo/app/foo/bar.js

Maybe I'm missing something around here but I don't understand why you can't just compile everything into one file with correct anonymous modules name that are equal to their full path starting with working directory... That is basically the only thing needed in real project. Maybe it is just because my project just lacks requireJS implementation on all of the files(and the only file to be optimized is one core file and it will grab all require dependencies) but currently it is not the case and this tool almost done what I've needed...

How to use `dir` based options

It looks like gulp-requirejs-optimize always passes the out option to requirejs.optimize(). I'd like to use the bundlesConfigOutFile option which only works with the dir option. The documentation seems to say this should be supported, but the code looks like it doesn't support setting dir at all.

Plugin braking the pipe. Plumber doesn't help

Hi I have huge watch task for my project and every single time i save on of js file with some error it's braking. I tried to fix it with plumber, but still brakes. On error is triggered but then it throws error either way. my code:

 return gulp.src(SCRIPTS_SRC + '*.js')
        .pipe(plugins.plumber({
            errorHandler: onError
        }))
        .pipe(plugins.requirejsOptimize())
        .pipe(plugins.plumber.stop())
        .pipe(gulp.dest(SCRIPTS_DEST));

Any ideas what might be the issue?

it seems that modules.name in options does not work as described in r.js optimizer

Here is my directory of workspace.
12

And I wrote the code in gulpfile.js as below.
11

I want only topics.js to be handled by this plugin. However, the plugin does not run, even I tried the values as below:
'topics.js'
'src/js/topics'
'src/js/topics.js'
'./src/js/topics'
'./src/js/topics.js'

As I understood(don't know it is correct or not), the modules which are defined in option.module should be handled by the plugin.

How to bundle all modules into single file with one top level wrapper.

I want to optimie all the modules into one singel file and a wrap over it.But its not doing that.
Here is the code.

`var gulp = require('gulp')
var requirejsOptimize = require('gulp-requirejs-optimize')

gulp.task('default', function () {
return gulp.src('src/**/*.js')
.pipe(requirejsOptimize())
.pipe(gulp.dest('build'))
})`

When i run the above task, it generates all files inidividually as they being assigned to requirejsOptimize() by gulp.src. If i use option 'warp: true', it wraps very file.
So i want all those files to be in a single file with only single wrap over it. How can i do that ? Thanks

How to exclude dependencies

While using r.js

I use this configuration as below to exclude date_picker, how do I do the same using this plugin

modules: [
{
name : 'main', // no i18n
include : ['main'], // no i18n
exclude: ['date_picker'] // no i18n
}
],

Build always fails when not wanting to use 'out', but 'dir' instead.

Here are the options I'm passing:

{
        appDir: dir',
        baseUrl: 'dir/js',
        dir: 'dir/bin',
        paths: {
            'ezpRequireJQuery': 'empty:'
        },
        modules: [
            {
                name: 'main'
            }
        ],
        mainConfigFile: 'dir/js/main.js',
        optimize: 'none'
}

I don't have 'out' supplied at all, but I get this error: "The "out" and "dir" options are incompatible. Use "out" if you are targeting a single file for optimization, and "dir" if you want the appDir or baseUrl directories optimized."

I tried setting 'out' to null or false, but I get the 'out must be a string' error.

StringMap expected string key

Somewhere in the process of this plugin, it's spewing out this error:

Error: StringMap expected string key

There are no errors in my javascript, and everything works absolutely fine. So I'm not sure what this error is on about. Furthermore, it also doesn't tell me where this error occurs, making it exceedingly hard to track down what's causing it - at least for me it is.

Is it possible to fix this? And in the mean time, work around it?

Let's have some version information as well, just in case it helps:
gulp-requirejs-optimize 1.2.0
npm 3.10.3
Gulp 3.9.1
Node 6.3.1
Windows 10

Passing illegal module identifiers to requirejs.optimize on Windows

Here is the context of this problem requirejs/r.js#907

I submitted a test project here to reproduce this problem.

Directly launching node r.js ... works fine, the windows path issue reproduces when running gulp build. gulp-requirejs-optimize invokes r.js using

requirejs.optimize(optimizeOptions, null, function(err) {
    error = err;
    cb();
});

where optimizeOptions were specified as the following object when processing xmod.js

{ mainConfigFile: 'config.js',
  logLevel: 2,
  baseUrl: 'c:\\Users\\Kontinuation\\Documents\\GitHub\\Vint\\reqjs\\app\\scripts\\',
  out: [Function],
  generateSourceMaps: false,
  include: 'libs\\xmod.js' }

The include property contains backslashes, which caused the problem, and the problem went away if I preprocess include property as unix path libs/xmod.js before calling optimize().

file.relative gives blackslash-separated paths, feeding such paths directly as module identifiers might cause unexpected problem. We might need to convert such windows-styled paths to module identifiers before calling into requirejs.

optimizer none still running optimize uglify within requirejs optimizer

I think theres a problem with the optimizer option, but it might be within requirejs optimize itself.

When I use the optimize option with 'none' within gulp-requirejs-optimizer, somewhere it changes to uglify.

  var requirejsOptimizeOptions = 
      {
        baseUrl: deploy.js,
        mainConfigFile: deploy.js + '/main.js',
        name: 'modules/init',
        out: 'main.js',
        optimizer: 'none' //see https://github.com/jrburke/r.js/blob/master/build/example.build.js for options
        ,logLevel:0
      };

  console.log(requirejsOptimizeOptions);
  var debug=require('gulp-debug');
  return gulp.src(tempsrc)
    .pipe(sourcemaps.init()) //sourcemaps.init({loadMaps:true})
    .pipe(debug())
    .pipe(requirejsOptimize(requirejsOptimizeOptions))
    .pipe(debug())
    //.pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(debug())
    .pipe(gulp.dest(deploy.js))

output looks like this:

C:\Projects\xxx\ContentWeb>gulp build-jsbundle --verbose
BASE_DEPLOY=PROD
[10:51:35] Using gulpfile C:\Projects\xxx\ContentWeb\gulpfile.js
[10:51:35] Starting 'set-jsbundle-deploy'...
[10:51:35] Finished 'set-jsbundle-deploy' after 64 µs
[10:51:35] Starting 'build-coffee'...
[10:51:35] processing coffee files at: FED/coffee/**/*.coffee
[10:51:35] writing files to: FED/obj/Assets/js
[10:51:35] Starting 'build-vendor'...
[10:51:35] processing vendor files at: FED/vendor/**/*
[10:51:35] writing files to: FED/obj/Assets/js/vendor
[10:51:35] Finished 'build-coffee' after 629 ms
[10:51:35] Finished 'build-vendor' after 688 ms
[10:51:35] Starting 'jsbundle-1'...
[10:51:35] building bundle
[10:51:35] input: FED/obj/Assets/js
[10:51:35] output: FED/obj/Assets/js/main.js
{ baseUrl: 'FED/obj/Assets/js',
  mainConfigFile: 'FED/obj/Assets/js/main.js',
  name: 'modules/init',
  out: 'main.js',
  optimizer: 'none',
  logLevel: 0 }
updated basePath. deploy.js=PROD/Assets/js
[10:51:35] gulp-debug:
cwd:   C:\Projects\xxx\ContentWeb
base:  C:\Projects\xxx\ContentWeb\FED\obj\Assets\js\
path:  C:\Projects\xxx\ContentWeb\FED\obj\Assets\js\main.js
stat:'[object Object]'

[10:51:35] Optimizing C:\Projects\xxx\ContentWeb\FED\obj\Assets\js\main.js
gulp-requirejs-optimizer:index.js:optimizeOptions { baseUrl: 'FED/obj/Assets/js',
  mainConfigFile: 'FED/obj/Assets/js/main.js',
  name: 'modules/init',
  out: [Function],
  optimizer: 'none',
  logLevel: 0,
  generateSourceMaps: true,
  preserveLicenseComments: false }

Tracing dependencies for: modules/init
Uglify file: modules/init.build.js
[10:51:43] gulp-debug:
cwd:   C:\Projects\xxx\ContentWeb
base:  C:\Projects\xxx\ContentWeb
path:  main.js

[10:51:43] gulp-debug:
cwd:   C:\Projects\xxx\ContentWeb
base:  C:\Projects\xxx\ContentWeb
path:  main.js


FUNCTION
----------------
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/vendor/jquery.min.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/vendor/jquery-ui.min.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/vendor/jquery.cookie.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/vendor/jquery.slides-3.0.4.min.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/vendor/jquery.equalizer.min.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/config.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/nav.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/vendor/jquery.mobile.events.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/modals.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/tabs.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/accordion.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/vendor/jquery.flexslider-min.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/vendor/tooltip.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/tooltips.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/vendor/jquery.validation.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/vendor/jquery.form.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/contact-form.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/gallery.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/slider.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/pagination.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/font-resize.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/alert-banner.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/messaging-banner.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/show-more-content.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/equal-heights.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/header.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/RegionVariableUrls.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/footer-decoration.js
C:/Projects/NationalGrid/ContentWeb/FED/obj/Assets/js/modules/init.js

[10:51:43] gulp-debug: 1 item
[10:51:43] gulp-debug: 1 item
[10:51:43] gulp-debug: 1 item
[10:51:43] Finished 'jsbundle-1' after 7.91 s
[10:51:43] Starting 'jsbundle-2'...
[10:51:43] Finished 'jsbundle-2' after 4.86 ms
[10:51:43] Starting 'build-jsbundle'...
[10:51:43] Starting 'include-vendor'...
[10:51:43] copying vendor files into PROD/Assets/js.
[10:51:43] Finished 'build-jsbundle' after 6.95 ms
[10:51:44] Finished 'include-vendor' after 1.26 s

C:\Projects\xxx\ContentWeb>

The line that starts with "gulp-requirejs-optimizer:index.js:optimizeOptions", i manually added into your index.js, just before calling requirejs.optimize, proving that whats going in for the object is optimize:'none'

option findNestedDependencies doesn't work

findNestedDependencies: true, paths: { 'some-module-1':'path/to/module-1' }
index.js
define([..], ()=> { ... require(['some-module-1'], ()=>{}) ... })

expect: 'some-module-1' inside bundle and full/path/to/module-1.js in log.

actual: module ignored.

Options to include path in module name

I want to optimize some modules with the requirejs optimizer, but ran into a problem concerning paths. The main.js entry point requires the component on /build/modules/, but the name of the optimized module does not match this path. The component file is loaded, but the function it defines isn't called.
main_component.js requires the components moduleA and moduleB, and the build's main.js requires the built main_component.js.

Code of ./build/main.js:

require(['./modules/main_component'], function () {
  console.log('main')
})

Code of ./build/modules/main_component:

/* component definitions ... */
define('main_component', // <- this needs to be 'modules/main_component' 
	['require','components/moduleA','components/moduleB'],
	function (require) { /* ... */}
)

Project structure:

/
|-- build
|    |-- modules
|    |   +-- main_component.js # optimized file
|    +-- main.js
|-- js
|    +-- modules
|        |-- components
|        |    |-- moduleA.js
|        |    +-- moduleB.js
|        +-- main_component.js
+-- index.html

Also, I'm using a gulp wrapper gulp-requirejs-optimize. This is my gulpfile:

var gulp = require('gulp')
var requirejsOptimize = require('gulp-requirejs-optimize')

gulp.task('default', function () {
  return gulp.src('js/modules/*.js')
	.pipe(requirejsOptimize({
	  optimize: 'none'
	}))
	.pipe(gulp.dest('build/modules'))
})

This is also a stackoverflow question: http://stackoverflow.com/questions/40742457/requirejs-optimizer-how-to-change-the-optimized-module-name

Performance compared to r.js CLI

When running the r.js optimizer from commandline, it takes about 10 seconds to build my project. With gulp-requirejs-optimize, it takes almost 2 minutes. I'm pretty sure that my setup is flawed; it would be great if someone could have a look.

First, this is my build.js for the CLI build:

({
  baseUrl: 'js',
  name: 'main',
  out: 'main-built.js',
  paths: {
    qrcode: 'libs/jquery.qrcode',
    // ...
  },
  shim: {
    // ...
  }
})

... which I call with this command: r.js -o build.js

And this is my gulp task:

gulp.task('rjs', function() {
  return gulp.src('js/**/*.js')
    .pipe(requirejsOptimize({
      optimize: 'none',
      useStrict: true,
      baseUrl: 'js',
      name: 'main',
      out: 'main-built.js'
      paths: {
        qrcode: 'libs/jquery.qrcode',
        // ...
      },
      shim: {
        // ...
      }      
    }))
    .pipe(gulp.dest('dist'));
});

The only obvious difference when compared to the samples in the docs I can see is that I pass in all .js files in the directory tree instead of single files/directories.

Any hint what I might be doing wrong here?

findNestedDependencies not correct in windows

My work dir tree like this:

default

src/module/a.js

define(function (require, exports, module) {
  console.log('module A');
});

src/module/b.js

define(function (require, exports, module) {
  console.log('module B');
});

src/sub-dir/main.js

require(['../requirejs-dev-config'], function () {
  require([
    '../module/a',
    '../module/b'
  ]);
});

src/main.js

require(['./requirejs-dev-config'], function () {
  require([
    './module/a',
    './module/b'
  ]);
});

src/requirejs-dev-config.js

// requirejs config file
// http://requirejs.org/docs/api.html#config
require.config({
  // clear browser's cache
  urlArgs: "bust=" + (new Date()).getTime(),

  baseUrl: '.',

  paths: {
    // http://jquery.com/
    jquery: '//cdn.bootcss.com/jquery/2.2.1/jquery.min',

    // http://jashkenas.github.io/underscore/
    underscore: '//cdn.bootcss.com/underscore.js/1.8.3/underscore-min'
  }
});

gulpfile.js

'use strict';

const gulp = require('gulp');
const gulpRequrejsOptimize = require('gulp-requirejs-optimize');

gulp.task('dist', () => {
  gulp.src([
      'src/**/main.js'
    ])
    .pipe(gulpRequrejsOptimize({
      baseUrl: 'src',
      optimize: 'none',
      findNestedDependencies: true,
    }))
    .pipe(gulp.dest('dist'));
});

The result as below

dist/main.js

// requirejs config file
// http://requirejs.org/docs/api.html#config
require.config({
  // clear browser's cache
  urlArgs: "bust=" + (new Date()).getTime(),

  baseUrl: '.',

  paths: {
    // http://jquery.com/
    jquery: '//cdn.bootcss.com/jquery/2.2.1/jquery.min',

    // http://jashkenas.github.io/underscore/
    underscore: '//cdn.bootcss.com/underscore.js/1.8.3/underscore-min'
  }
});
define("requirejs-dev-config", function(){});

define('module/a',['require','exports','module'],function (require, exports, module) {
  console.log('module A');
});
define('module/b',['require','exports','module'],function (require, exports, module) {
  console.log('module B');
});
require(['./requirejs-dev-config'], function () {
  require([
    './module/a',
    './module/b'
  ]);
});
define("main.js", function(){});

dist/sub-dir/main.js

require(['../requirejs-dev-config'], function () {
  require([
    '../module/a',
    '../module/b'
  ]);
});
define("sub-dir\main.js", function(){});

The dist/sub-dir/main.js is not include the nested dependencies. In mac os, it's right.But in windows, it's incorrect.

build not recognizing paths correctly

I could be setting this up wrong, but here is my issue:

I am noticing in the error log that it is looking for a file that doesn't exist.
Error: Error: ENOENT: no such file or directory, open 'path/to/project/assets/js/marionette.js'

In my main.js, I have Marionnette defined as such:

require.config({
    baseURL:'assets/js',
    paths:{
        ...
        marionette  : "vendor/backbone.marionette",
        ...
   }
   shim: {
        ...
        backbone: {
            deps: ['jquery', 'underscore'],
            exports: 'Backbone',
        },
        marionette: {
            deps: ['backbone'],
            exports: 'Marionette',
        },
        ...
    }
});

I looks like the plugin is skipping the config completely (the file should be backbone.marionette.js), since it is not looking in the /vendor/ folder nor is it looking for the right file name.

Here is my simple gulp task:

gulp.task('rqs', function () {
  return gulp.src('assets/js/main.js')
    .pipe(requirejsOptimize(function (file) {
      return {
        siteRoot: '../../',
      };
    }))
  .pipe(gulp.dest('dist'));
});

Am I doing something wrong? Thanks!

Include dependencies in a multi-page webapp

Hi,

I have the exact contrary of issue 8: I cannot seem to include dependencies in my modules.

I'm trying to optimize a multi-page webapp, structured like this:

/bower_components
/src/home/home.html
/src/home/home.js
/src/home/homeCtl.js
/src/books/books.html
/src/books/books.js
/src/books/booksCtl.js
/src/common.js
/dist

common.js holds RequireJS' configuration, including paths to bower components:

requirejs.config({
  paths: {
    jquery: '/bower_components/jquery/dist/jquery.min',
    ...
  }
}});

Since I need one configuration and multiple 'main' files, home.js is shaped like this:

require(['../common']), function() {
  require(['homeCtl']);
});

and homeCtl.js is like this:

define(['jquery'], function($) {
  ...
});

The problem ism when I try to optimize the home.js module I get a file with just its content, while I was expecting it to traverse all its dependencies to include them.

gulp.src('src/home/home.js', {base: 'src'})
  .pipe(gulpRequirejsOptimize())
  .pipe(gulp.dest('dist'))

Result:

require(["../common"],function(){return require(["home/homeCtl"])}),define("homehome.js",function(){});

Am I doing something wrong? Thanks in advance!

Named module not found

When I include a module that is defined like so:

define("foo", [ ], function() {
  return {
    // ...
  };
});

And I clude that module early in my application, it works fine. When I then also include the module by name foo rather than path path/to/foo, it doesn't work.

Error: ENOENT: no such file or directory

It works fine when I don't build my project and let RequireJS do its thing in the browser.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.