Giter Site home page Giter Site logo

grunt-babel's Introduction

This readme is for grunt-babel v8 + Babel v7 Check the 7.x branch for docs with Babel v6

grunt-babel Build Status

Use next generation JavaScript, today, with Babel

Issues with the output should be reported on the Babel issue tracker.

Install

For Babel 7.x and grunt-babel v8

$ yarn add --dev grunt-babel @babel/core @babel/preset-env

For Babel 6.x and grunt-babel v7

$ yarn add --dev grunt-babel@7 babel-core babel-preset-env

Note: See the 7.x branch for more examples of usage of Babel 6.x. This README is primarily applicable for Babel 7.x

Usage

Option with load-grunt-tasks

require('load-grunt-tasks')(grunt); // npm install --save-dev load-grunt-tasks

grunt.initConfig({
  babel: {
    options: {
      sourceMap: true,
      presets: ['@babel/preset-env']
    },
    dist: {
      files: {
        'dist/app.js': 'src/app.js'
      }
    }
  }
});

grunt.registerTask('default', ['babel']);

Option with loadNpmTasks

grunt.initConfig({
  babel: {
    options: {
      sourceMap: true,
      presets: ['@babel/preset-env']
    },
    dist: {
      files: {
        'dist/app.js': 'src/app.js'
      }
    }
  }
});

grunt.loadNpmTasks('grunt-babel');

grunt.registerTask('default', ['babel']);

Options

See the Babel options, except for filename which is handled for you.

License

MIT © Sindre Sorhus

grunt-babel's People

Contributors

danez avatar dependabot[bot] avatar es128 avatar hzoo avatar idleberg avatar loganfsmyth avatar redonkulus avatar renanlopescoder avatar sebmck avatar sibiraj-s avatar sindresorhus avatar winterbe avatar xhmikosr 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grunt-babel's Issues

sourceMap is not working

Setting sourceMap equals true generate a file .js.map, but its contents have just "[object Object]".
I'm not pretty sure if it is an error on 6to5 or in my configuration or in grunt-6to5.

My Gruntfile looks like this:

 grunt.initConfig({
        '6to5': {
            options: {
                sourceMap: true
            },
            dist: {
                files: {
                    'dist/app.js': 'src/classes.js'
                }
            }
        }
    });

Grunt Babel Taking 6 Seconds Per File

I'm trying to use Babel in my grunt build process to transpile my .js project files from ES6 to ES5. I have a watch task watching my .js directory for changes and when changes are detected, I run the babel task.

For some reason though, changing just one .js file takes anywhere between 6-10 seconds to complete. I have a feeling it's transpiling the entire project, but I'm not sure. My Gruntfile.js looks like this:

grunt.initConfig({
  watch: {
    babel: {
      files: ["<%= yeoman.app %>/scripts/**/*.js"],
      tasks: ["babel"]
    },
    livereload: {
      options: {
        livereload: LIVERELOAD_PORT
      },
      files: [
        "{.tmp,<%= yeoman.app %>}/scripts/**/*.js",
      ]
    }
  },
  babel: {
    options: {
      sourceMap: true,
      presets: ['es2015']
    },
    dist: {
      files: [
        {
          expand: true,
          cwd: '<%= yeoman.app %>/scripts/',
          src: ['**/*.js'],
          dest: '.tmp/scripts/'
        }
      ]
    }
  }
});
grunt.registerTask("serve", function(target) {
  return grunt.task.run(["watch"]);
});

When I run grunt serve and change a file it logs the execution time:

Running "babel:dist" (babel) task

Done, without errors.

Execution Time (2015-12-01 11:57:54 UTC)
babel:dist 6.7s ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 100%
Total 6.7s

But when I use babel-cli in my terminal, it transpiles in milliseconds, almost instantaneously even:

babel --presets es2015 script.js --out-file transpiled.js

Surely this is way too long. Am I doing something wrong here.

Any help is appreciated. Thanks in advance!

Commit ea524a8 breaks source maps

Commit ea524a8 broke my build. I have a file at:
"app/modules/components/base/item-panel/page-view/alto/alto-highlight-fragments.js"
that's transformed to:
"app/.tmp/processed-pre-ng-annotate/modules/components/base/item-panel/page-view/alto/alto-highlight-fragments.js"
to be later passed to grunt-ng-annotate. Before the mentioned commit I got an inline source map with:

"file": "app/modules/components/base/item-panel/page-view/alto/alto-highlight-fragments.js"

and now I just get:

"file": "alto-highlight-fragments.js"

My full grunt-babel config:

babel:     options: {
        sourceMap: 'inline',
        sourceRoot: path.join(__dirname, '/../../'),
        retainLines: true,
        loose: [
            // Speed up for-of on arrays by not using the iterator directly.
            'es6.forOf',
        ],
    },

    app: {
        files: [
            {
                expand: true,
                src: [
                    'app/app.js',
                    'app/{modules,lib}/**/*.js',
                ],
                rename: function prependTmpProcessed(dest, src) {
                    return src
                        .replace(/^app\/app\.js/, 'app/.tmp/processed-pre-ng-annotate/app.js')
                        .replace(/^app\/modules\//, 'app/.tmp/processed-pre-ng-annotate/modules/')
                        .replace(/^app\/lib\//, 'app/.tmp/processed/lib/');
                },
            },
        ],
    },
},

Support for minification+source maps.

Would be nice if one could minify the ES5 output files + being able to map the minified files back to the original ES6 source files. Unsure if this is a grunt-6to5 task, or if 6to5 should handle this?

Whitelisting react throws error

Hey, I'm trying to use the react transformer alone, without ES6 transformers, etc,

When using babel CLI, this works:

babel --whitelist=react libraries.jsx

But, using grunt-babel, I get this:

Running "babel:chrome" (babel) task
Warning: src/chrome/components/menus/libraries.jsx: Cannot read property 'this' of undefined Use --force to continue.

I tried whitelisting other transformers such as es6.arrowFunctions and it works.
Also, using react along with other transformers works (i.e. not using whitelist option at all).

And Oh, it works on some files, and not on others, the file it's failing to work on is here:
https://github.com/mdibaiee/devtools-prototyper/blob/f6be2a7f738268a2b888805865fc07307587928a/src/chrome/components/menus/libraries.jsx

My grunt config: https://gist.github.com/mdibaiee/467315635ad487e53ff4

Support compiling many files into one?

Is it only possible to compile single files to single files? It's unclear if this is possible, e.g.

    babel: {
        options: {
            sourceMap: true,
        },
        src: {
            files: {
                './static/js/main.js': [
                    './static/es6/**/*.{es6,js6,jsx}',
                    './static/es6/*.{es6,js6,jsx}'
                ]
            }
        },
    };

keep dot separated file

i have a file app.collection.js and when running grunt babel, its getting converted app.js . How to fix this ?

No minimatch support?

I have a deep directory structure. I cannot add each file one by one. Why don't you make use of the minimatch library which is already supported by Grunt?

grunt.initConfig({
        babel: {
            options: {
                sourceMap: true,
                presets: ['es2015']
            },
            dist: {
                files: {
                    'build/**/*.js': 'src/**/*.js'  // <-- doesn't work
                }
            }
        }
    });

grunt-babel example from readme generates exception

'use strict';

module.exports = function(grunt) {

require('load-grunt-tasks')(grunt); // npm install --save-dev load-grunt-tasks

grunt.initConfig({
    babel: {
        options: {
            sourceMap: true
        },
        dist: {
            files: {
                'dist/app.js': 'src/app.js'
            }
        }
    }
});

grunt.registerTask('default', ['babel']);
};

generates exception:

grunt
Running "babel:dist" (babel) task
Warning: path must be a string Use --force to continue.

Aborted due to warnings.

grunt babel configuration does not work

Test environment 


  • OS : windows 7
  • "grunt": "^0.4.5", - 
  • "grunt-babel": "^5.0.3", 

Test


My configuration were like the below, which is the same in README.md

module.exports = function (paths) {
    'use strict';
    var src_jsx = paths.src_jsx;
    var dest = paths.dest;

    return {
        babel: {
            options: {
                sourceMap: true
            },
            dist: {
                files: {
                    'dist/app.js': 'src/app.js'
                }
            }
    }

so, I debugged.(But, I'm kind of newbie of nodejs) I figured out that the babel.js has a bug

  • c:\<project>\node_modules\grunt-babel\tasks\babel.js

My Fix


I fixed it like the below, and also fix the configuration for babel

  • this.files.forEach --> this.data.files.forEach
  • files configuration


module.exports = function (grunt) {


    grunt.registerMultiTask('babel', 'Transpile ES6 to ES5', function () {
        var options = this.options();

               // this.files --> this.data.files
        this.data.files.forEach(function (el) {
            delete options.filename;
            delete options.filenameRelative;

            

            options.sourceFileName = path.relative(path.dirname(el.dest), el.src[0]);
            if (process.platform === 'win32') {
                options.sourceFileName = options.sourceFileName.replace(/\\/g, '/');
            }
            options.sourceMapTarget = path.basename(el.dest);

            var res = babel.transformFileSync(el.src[0], options);

            var sourceMappingURL = '';
            if (res.map) {
                sourceMappingURL = '\n//# sourceMappingURL=' + path.basename(el.dest) + '.map';
            }

            grunt.file.write(el.dest, res.code + sourceMappingURL + '\n');

            if (res.map) {
                grunt.file.write(el.dest + '.map', JSON.stringify(res.map));
            }
        });
    });
};


module.exports = function (paths) {
    'use strict';
    var src_jsx = paths.src_jsx;
    var dest = paths.dest;
return {
    babel: {

        options: {
            sourceMap: true,
        },
       
        files : [{
            src: ["src/spikeview.js"],
            dest: 'src/ddd.js',
            
        }],
    }
}

}



Now it works.

I have seen many blogs who set the configuration of babel differently and works. So, I can't sure whether this is the really issue or not.

Anyhow, I hope this issue will be fixed for Windows which is my main OS :)

grunt-babel not including import statement>?

I get no errors and the task says that it has completed, am I missing something?

module.exports = function(grunt) {

  grunt.config.set('babel', {
    options: {
      sourceMap: true,
      presets: ['babel-preset-es2015','react']
    },
    dev: {
      files: {
        'assets/js/app.js': 'assets/js/src/app.jsx'
      }
    }
  });

  grunt.loadNpmTasks('grunt-babel');

};'

Wrong `sources` in sourcemap

Folder structure:

Gruntfile.js
dist/
- main.js
- main.js.map
src/
- main.js

Gruntfile.js

grunt.initConfig({
    babel: {
        options: {
            sourceMap: true
        },
        js: {
            files: [{
                expand: true,
                cwd: "src/",
                src: "main.js",
                dest: "dist/"
            }]
        }
});

main.js.map

{"version":3,"sources":["src/main.js"],...

Shoulden't sources be ["../src/main.js"]?

copy file into current directory

Is there any way to pass in an array of files, and just have them output to that file's directory in a directory called 'build', or do you have to specify each destination by name?

Too slow on load

I've just got some stats for babel execution and seems that it's too slow on load especially. Shouldn't it take much more time to compile and less time to load?

image

These are stats for a single concat'd javascript file (~10kB, 300 lines).

Unmatched file source glob patterns prevent further compilation

If I interpret it correctly, the convention in grunt tasks is to skip unmatched glob patterns given as file sources unless nonull is passed.

In grunt-6to5, an unmatched glob pattern causes processing to stop. This could be trivially fixed by just checking src for undefined before processing it, if nonull is unset. This could prevent unexpected task failures when setting up new projects where the target files don't exist yet, and make it simpler to share configs.

Support for multiple sources (array)

Add support for multiple sources. (Seems only the first one is added to the .map file in the current version.)

module.exports = {
    options: {
        sourceMap: true
    },
    dist: {
        files: {
            'build/dist.js': [
                webroot/js/source1.js,
                webroot/js/source2.js,
                some/js/file.js,
            ]
        }
    }
};

Issue with checking EOL-LAST by Eslint

I have this piece of code

  gulp.src(files)
      .pipe($.babel({sourceMap: false}))
      .pipe(reload({stream: true, once: true}))
      .pipe($.eslint(options))
      .pipe($.eslint.format())
      .pipe($.if(!browserSync.active, $.eslint.failAfterError()));

and after running gulp task i am receiving this error (no matter what i do with ES6 file)

  error  Newline required at end of file but not found  eol-last

I'd like to remind that my file has eol-last. I tried to investigate the problem and i figured out that babel cut off every white-char after last "normal char".

What can you tell me about this issue? Thank you in advance

Problem with source map comment at EOF

My project is using multiple JS files, most not being compiled by babel (only using 1 for now), but are being ajax'd in and eval'd because of the framework. In order to debug, I have to use:
//# sourceURL=someFile.js

What this does is put all the eval'd files into 1 file someFile.js which appears in the sources tab under chrome dev tools so it can be debugged.

When I include my sources, if the file I am compiling with babel is not the last file to be included in this 'someFile.js', the first line of the next file to be concatenated to the file will be commented out which will cause problems.

For example:
//# sourceMappingURL=event.service.js.map;require([

This causes an error because require is commented out since there is not a \n at the end of the line. It should read:
//# sourceMappingURL=event.service.js.map;
require([

Add a changelog?

Could this project start maintaining a changelog? It is kind of hard to see what is changing between versions.

Using babel in a development env

So I am new to the whole grunt thing so forgive me and I dont know where to put it but I am wondering how would I use the code in development env. I understand how to use in deployment but I am having trouble using in a development env like localhost.

Errors out on array comprehension

Array comprehension transpilation is not working:

function nums() {
  return [1,2,3];
}

var res = [for (n of nums()) n * 2];

console.log(res);

gives:

$ grunt babel
Running "babel:dist" (babel) task
Warning: src/arraycomp.js: Unexpected token (6:11)
  4  | }
  5  |
> 6  | var res = [for (n of nums()) n * 2];
     |            ^
  7  |
  8  | console.log(res);
  9  |  Use --force to continue.

Aborted due to warnings.

It works fine here

Unexpected result when using RequireJS

I am writing a RequireJS app using AngularJS and grunt-babel to transpile. Everything works well except for my config.js file. Here is the original file:

import * as angular from 'angular'
import * as app from 'app'

var $html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function() {
  // bootstrap the app manually
  angular.bootstrap(document, ['SampleApp']);
});

require.config({
  paths: {
    angular: '../lib/bower_components/angular/angular',
    ngRoute: '../lib/bower_components/angular-route/angular-route.min'
  },
  shim: {
    'angular' : {'exports' : 'angular'},
    'ngRoute': ['angular']
  }
});

And here is the file after I run grunt-babel:

define(['exports', 'angular', 'app'], function (exports, _angular, _app) {
  'use strict';

  var $html = _angular.element(document.getElementsByTagName('html')[0]);
  _angular.element().ready(function () {
    // bootstrap the app manually
    _angular.bootstrap(document, ['SampleApp']);
  });

  require.config({
    paths: {
      angular: '../lib/bower_components/angular/angular',
      ngRoute: '../lib/bower_components/angular-route/angular-route.min'
    },
    shim: {
      'angular': { 'exports': 'angular' },
      'ngRoute': ['angular']
    }
  });
});

The issue is that require.config() needs to be outside of define() like this:

define(['angular', 'app'], function(angular, app) {
  var $html = angular.element(document.getElementsByTagName('html')[0]);
  angular.element().ready(function() {
    // bootstrap the app manually
    angular.bootstrap(document, ['SampleApp']);
  });
});

require.config({
  paths: {
    angular: '../lib/bower_components/angular/angular',
    ngRoute: '../lib/bower_components/angular-route/angular-route.min'
  },
  shim: {
    'angular' : {'exports' : 'angular'},
    'ngRoute': ['angular']
  }
});

Here is my Gruntfile.js:

module.exports = function(grunt) {

  grunt.initConfig({
    babel: {
      options: {
        sourceMap: true,
        //This is important because babel's default is commonjs
        modules: "amd"
      },
      dist: {
        files: {
          '../final/config.js': '../app/config.js',
          '../final/app.js': '../app/app.js',
          '../final/controllers/View1Ctrl.js': '../app/controllers/View1Ctrl.js',
          '../final/controllers/View2Ctrl.js': '../app/controllers/View2Ctrl.js'
        }
      }
    }
  });

  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  grunt.registerTask('default', ['babel']);
};

Is there any way to specify that the require.config() function should be outside of the define() function?

Warning: path must be a string Use --force to continue.

I have grunt task for babel as it's described on Babel official page:

babel : {
  options: {
      sourceMap: true
    },
  dist : {
    files : {
      'app/scripts/controllers/target-babel.js' : 'app/scripts/controllers/src.js'  
    }
  }
},

After running grunt babel I get:

Running "babel:dist" (babel) task
Warning: path must be a string Use --force to continue.

Aborted due to warnings.

grunt-bable's compile is terrible slowly

recently, i have used grunt-beble to transform es6 to es5 in my project. it worked but i found that the compile time is so long.it took 6~7 seconds to compile one es6 file which only has one line code in it.

here's my npms
"devDependencies": {
"babel-preset-es2015": "^6.1.4",
"grunt-babel": "^6.0.0",
"time-grunt": "^1.2.2"
}

my gruntfile:
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),

    babel: {
        test: {
            options: {
                presets: ['es2015'],
                compact: false
            },
            files: [{
                expand: true,
                cwd: 'test',
                src: ['*.es6'],
                dest: 'dist',
                ext: ".js"
            }]
        }
    }
});

and the es6 file's contents
let a = 1;
let b = 2;

the compile result:
λ grunt
Running "babel:test" (babel) task

Done, without errors.

Execution Time (2015-11-12 03:06:05 UTC)
loading tasks 1s ██████████████████████████ 13%
babel:test 7s ████████████████████████████████████████████████████████████
Total 8s

i have tried to find the reason in google,but no one mentioned this situation。
has anybody comes my question?
much thanks!

Possible to update babel-core dependency?

It seems there has been quite a bit of development going on in core that's not yet available for grunt-babel users. At the time of writing this babel-core is at version 5.6.4 while grunt-babel on uses version 5.0.0.

I'm particularly missing 5.3.0 and 5.3.1 which has references to speed and performance in the changelog :)

[Grunt] Path must be a string

Hi there,

I have the next code at the Gruntfile.js

require("load-grunt-tasks")(grunt);

grunt.initConfig({
  "babel" : {
    options : {
      sourceMap : true
    },
    dist : {
      files : {
        "dist/app.js" : "src/app.js"
      }
    }
  }
});

grunt.registerTask("default", ["babel"]);

I have this in src/app.js

class App{

  constructor( container ){

    this._container = document.getElementById( container );
  }

  getContainer(){
    return this._container;
  }
}

And when I tried to execute grunt using babel, I got this error:

Loading "Gruntfile.js" tasks...ERROR
>> ReferenceError: grunt is not defined
path.js:8
    throw new TypeError('Path must be a string. Received ' +
    ^

TypeError: Path must be a string. Received true
    at assertPath (path.js:8:11)
    at Object.posix.join (path.js:479:5)
    at Object.file.exists (/home/ismael/projects/babel/node_modules/grunt/lib/grunt/file.js:381:28)
    at task.loadTasks (/home/ismael/projects/babel/node_modules/grunt/lib/grunt/task.js:371:18)
    at Array.forEach (native)
    at Task.task.init (/home/ismael/projects/babel/node_modules/grunt/lib/grunt/task.js:457:33)
    at Object.grunt.tasks (/home/ismael/projects/babel/node_modules/grunt/lib/grunt.js:120:8)
    at Object.module.exports [as cli] (/home/ismael/projects/babel/node_modules/grunt/lib/grunt/cli.js:38:9)
    at Object.<anonymous> (/usr/local/lib/node_modules/grunt-cli/bin/grunt:45:20)
    at Module._compile (module.js:397:26)

What I'm doing wrong, and how can I fix it?

Thanks, Jaster

Getting `Unknown option: base.module`

Hi, when I add the modules: 'umd option I get the a Unknown option: base.module error. When I remove it, everything works fine.

In my Gruntfile:

        babel: {
            dist: {
                options: {
                    sourceMap: true
                    , presets: ['es2015']
                    , modules: 'umd'
                }
                , files: {
                    'dist/myfile.js': 'src/myfile.js'
                }
            }
        }

I've also tried moving the options object outside of the dist sub-task.

Am I doing something wrong here?

Divergent behavior in AMD

Hi everyone,

grunt-babel (v4.0.0) gives me a different output than babel (v4.7.16).

The script

import foo from "foo";
import foo2 from "foo2";
console.log(foo);
console.log(foo2);

transpiles to

define(["exports", "foo", "foo2"], function (exports, _foo, _foo2) {
  "use strict";

  var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };

  var foo = _interopRequire(_foo);

  var foo2 = _interopRequire(_foo2);

  console.log(foo);
  console.log(foo2);
});

with babel -m amd -e which is suitable, but to

"use strict";

var _interopRequire = function(a) {
    return a && a.__esModule ? a["default"] : a;
}, foo = _interopRequire(require("foo")), foo2 = _interopRequire(require("foo2"));

console.log(foo), console.log(foo2);

with grunt-babel, using

        babel: {
            options: {
                experimental: true,
                compact: false
            },
            scripts: {
            },
            modules: {
                options: {
                    modules: "amd"
                }
            }
        }

Is this an intended behavior?

grunt-babel fails with config from README

Running "babel:dist" (babel) task
Warning: Path must be a string. Received undefined Use --force to continue.

config:

        babel: {
            options: {
                sourceMap: true,
                presets: ['es2015']
            },
            dist: {
                files: {
                    'dist/app.js': 'src/app.js'
                }
            }
        },

How to: .es6 to .js

How do I use grunt-6to5 to compile one directory to another directory (including sub-folders), and instead of compiling the .es6 from to .es6, I want them to be .js file. Can you tell me how to do this? I can't figure it out. It seems like most people want to compile from .es6 to .js, so I am wondering if this is supported. Or, is this something that I should just do with another grunt task?

Path must be a string. Received undefined

I got the following error when trying to run the suggested code on grunt.

Running "babel:dist" (babel) task
Warning: Path must be a string. Received undefined Use --force to continue.

Any help?

sourceMap: "inline" option generates both "inline" and external file

I have following settings:

"6to5": {
            options: {
                sourceMap: "inline",
                modules: "amd",
                experimental: true
            },
            src: {
                files: [{
                    expand: true,
                    cwd   : "src/",
                    src   : [ "**/*.{jsx,es6}" ],
                    dest  : "dist/",
                    ext   : ".js"
                }]
            }
        }

And in my dist/ directory I always get compiled file with inline sourceMap (correct) but also .js.map file. Why?

Babel and grunt-watch

Hello!

I've got a project that uses connect -> watch -> babel in the dev environment. When I first run grunt server, it transpiles the es6->js successfully.

The watch works in that it sees changes to the es6 file and runs the babel tasks. The js file changes somehow, because grunt sees a change and refreshes the page with livereload, but the changes to the es6 file are not reflected in the js file.

My inexperienced assumption is that the js file is being rewritten, but without the new changes to the es6 file. Any thoughts?

A truncated copy of my gruntfile:

grunt.registerTask('server', [
    'sass',
    'babel',
    'connect:server',
    'watch'
]);

grunt.initConfig({
    babel: {
        options: {
            sourceMap: true
        },
        all: {
            files: [{
                expand: true,
                cwd: 'dev/js/site',
                src: ['**/*.es6'],
                dest: 'dev/js/site',
                ext: '.js'
            }]
        }
    },
    watch: {
        livereload: {
            options: { livereload: true },
            files: ['dev/css/*.css', 'dev/js/site/*.js', 'dev/**/*.html']
        },
        sass: {
            files: 'dev/scss/*.scss',
            tasks: ['sass']
        },
        babel: {
            files: 'dev/js/site/*.es6',
            tasks: ['babel']
        }
    },
    connect: {
        server: {
            options: {
                port: 8888,
                hostname: '*',
                livereload: true,
                open: true,
                base: 'dev'
            }
        }
    }
}

grunt-babel fails when used with grunt-contrib-watch with spawn set to false

I am using grunt-babel together with grunt-contrib-watch to transpile .jsx files when they are changed.

On Windows running tasks with grunt-contrib-watch is reeeeally slow without setting options.spawn to false. However, when grunt-babel is run with the said option set to false, the following happens:

>> File "foo/bar.jsx" changed.
Loading "babel.js" tasks...ERROR
>> TypeError: undefined is not a function
Warning: Task "babel" failed.

The same task works fine when ran manually from the cmd-line with grunt babel and it also works when spawn is set to true. Neither is really an optimal solution, first one for obvious reasons and the second one because it takes like 45 seconds to transpile 1 file. Simplified configuration example:

watch task:

        watch: {
            foo: {           
                files: ['foo/bar.jsx'],
                tasks: ['babel'],
                options: {
                    spawn: false
                }
            }
        }

grunt-babel task:

        babel: {
            options: {
                sourceMap: false
            },
            backend: {
                files: {
                    'foo/bar.js': ['foo/bar.jsx']
                }
            }

        }

(I am aware that the options.spawn documentation does mention that tasks are more prone to failing without spawning a child process, but grunt-babel has so far been the only one to fail consistently from hundreds of tasks)

Windows 10, Grunt v0.4.5, Node 0.12.7

Ability to specify source and destination directories

The 6to5 command line tool lets you "compile the entire src directory and output it to the lib directory"

$ 6to5 src --out-dir lib

while grunt-6to5 seems to work only if you list each individual file. (Unless I'm missing something obvious?)

Output both amd and commonjs formats?

Is there (plans to / already in place / some other way) to be able to output both amd and commonjs formats? I wish to be able to write some ES6 modules and use the code both client and server-side.

Two constraints I want to meet while doing this are

  1. Use the more "native" module system in each respective environment
  2. Minimize my toolchain

Grunt is still a bit new to me, so please forgive me if there's already an obvious way I'm just missing.

A custom process function

Currently there is no information about which files have been translated
Would like to do any custom processing before... (see grunt-contrib-concat ) like

module.exports = function (grunt) {
    var done = this.async();

    grunt.initConfig({
        6to5: {
            build: {
                files: [{
                    expand: true,
                    cwd   : 'trunk/',
                    dest  : 'cache/trunk/',
                    src   : [ '**/*.js' ]
                }]
            },

            process: function (src, path_to_file) {
                grunt.log.write(path_to_file);
                done();

                return src;
            }
        }
    });
};

It will be convenient for debugging or custom wrappers.

1420849930456

Warning: Couldn't find preset Use

I just upgraded to grunt-babel 6.0.0. I changed my Gruntfile to match the example in the readme:

babel: {
  options: {
    presets: ["babel-preset-es2015"],
    sourceMap: true,
    compact: false
  },
  main: {
    files: {
      "./resources/public/js/skimap.js": "./tmp/skimap.js"
    }
  }
}

When I try to run it I get the following Error:

Running "babel:main" (babel) task
Warning: Couldn't find preset Use --force to continue.

Aborted due to warnings.

Optional 'runtime' not including corejs; require is undefined

I am setting the options optional: ['runtime'] which has the benefits described here. On that page it says the runtime optional transformer does three things, including using the module helpers instead of inline (it does this) but it is not including core.js.

When I run grunt the filesize doesn't increase to indicate anything was added (core.js) and I get the error in console Uncaught ReferenceError: require is not defined.

sourceMappingURL Directive Missing

Hi, I'm not sure if this issue needs to be raised here or in the main 6to5 repo.

I've set sourceMap: true in my gruntfile options, and the source maps are produced, but the sourceMappingURL directive is not added to the output JS files. sourceMap: 'inline' appears to add the directive correctly.

Unknown option: base.optional

When trying to do a grunt serve I'm using grunt-babel to compile the ES6 but getting the strangest error.

Running "babel:server" (babel) task
Warning: [BABEL] server/api/Watchlist/Watchlist.controller.js: Unknown option: base.optional Use --force to continue.

Here's the babel section within the grunt file

babel: {
  options: {
    sourceMap: true
  },
  server: {
    options: {
      optional: ['runtime']
    },
    files: [{
      expand: true,
      cwd: '<%= yeoman.server %>',
      src: ['**/*.{js,json}'],
      dest: '<%= yeoman.dist %>/<%= yeoman.server %>'
    }]
  }
},

Babel & babel-grunt are both installed --save-dev.

Anyone run into this one before?

loading performance

I'm using jit-grunt which has a great impact on every package but grunt-babel:

loading grunt-newer            23ms  ▇▇ 2%
newer:concat:vendor            25ms  ▇▇ 2%
loading grunt-contrib-concat   32ms  ▇▇▇ 2%
concat:app                    140ms  ▇▇▇▇▇▇▇▇▇▇ 10%
newer:concat:debug             15ms  ▇▇ 1%
loading grunt-babel           671ms  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 47%
babel:app                     426ms  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 30%
hash:js                        28ms  ▇▇ 2%

Did I find any issue there?

Unable to use standard grunt files settings

I'm integrating react with my project and want to have grunt compile all my jsx sources to js. New sources are being added regularly, so I'm trying to use grunt's wildcard notation.

It's possible I have an unusual configuration, but looking at the source here, using el.src[0] appears to be incorrect. I have this in my Gruntfile for babel. It's similar to many of the other sections for things like less and those work fine:

                files : [
                    {
                        src  : ['*.jsx'],
                        dest : '<%= rr.scripts %>/r/',
                        cwd  : '<%= rr.xscripts %>/'
                    }
                ]

And I added grunt.log.write(JSON.stringify(el)); at line 12 of babel.js and I see this output:

{"src":["Blurb.jsx","Experiment1.jsx","HelloWorld.jsx","IconList.jsx","InputButton.jsx","Popover.jsx","Spinner.jsx","StandardButton.jsx","TBContainer.jsx","TBRow.jsx","TestWidget.jsx","TodoList.jsx"],"dest":"../public/static/js/r/","cwd":"../public/static/jsx/","orig":{"src":["*.jsx"],"dest":"../public/static/js/r/","cwd":"../public/static/jsx/"}}Warning: ENOENT, no such file or directory 'Blurb.jsx' Use --force to continue.

Clearly, grunt is expecting plugins to iterate over the "src" attribute and join it with the "cwd" attribute. Those are in fact the components I want to compile.

I apologize for not making a test case, but I am not that familiar with node development. I could probably manage to make a patch for this and test it against my use case if it would help.

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.