ES6 - Using babel/traceur with jQuery plugins

2019-06-24 03:08发布

问题:

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

回答1:

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