简体   繁体   中英

ES6 - Using babel/traceur with jQuery plugins

I want to be able to write ES6 with jQuery plugins and compile the code down to ES5 using Gulp Babel, without having to use Browserify to make them work.

For example, I may have a class like this:

import $ from 'jquery';
import somePlugin from 'somePlugin';

class myClass {
    constructor(options) {
        this.defaults = {
            $body: $('body')
        };

        this.options = $.extend(this.defaults, options);

        $body.somePlugin();
    }
}

I can get this to work if I use Babelify but I'd prefer to find a way where I do not have to depend on another process. When I just use Babel, I get this error in the console: Uncaught ReferenceError: require is not defined . I checked the code and it looks like it's turning the imports into requires.

Is there a way around this or will I have to stick with using Browserify (Babelify) to compile the JavaScript?

EDIT: I am currently using browserify-shim to make the jQuery plugins work too

EDIT2: No this is not about RequireJS - I'm trying to remove the use of Browserify with Babel

Answering my own question here. I did some digging and it looks like the best way of dealing with this issue at the moment is using jspm with the es6-module-loader.

Gulpfile:

var gulp    = require('gulp');
var del     = require('del');
var shell   = require('gulp-shell');

gulp.task('clean', function(cb) {
  del('dist', cb);
});

gulp.task('default', ['clean'], shell.task([
  'jspm bundle-sfx app/main -o dist/app.js',
  './node_modules/.bin/uglifyjs dist/app.js -o dist/app.min.js',
  './node_modules/.bin/html-dist index.html --remove-all --minify --insert app.min.js -o dist/index.html'
]));

HTML:

<head>
    <title>ES6</title>
    <script src="jspm_packages/system.js"></script>
    <script src="config.js"></script>
    <script>
        System.import('app/main');
    </script>
</head>

The repo I created here will also show you how to do it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM