ES6 - Using babel/traceur with jQuery plugins

心不动则不痛 提交于 2019-12-10 15:58:53

问题


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



来源:https://stackoverflow.com/questions/30512650/es6-using-babel-traceur-with-jquery-plugins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!