import and export a jquery function

14,720

First you need to wrap this code in a function. Then you export the function. Finally you import it in main.js:

custom.js

export function foo () {
    $('.nav.navbar-nav > li').on('click', function(e) {
        $('.nav.navbar-nav > li').removeClass('active');
        $(this).addClass('active');
    });
}

main.js

import {foo} from 'custom'

foo();

ECMA SCRIPT 6 modules

Also notice that you need a module loader (like webpack/systemjs/requirejs etc.), as well as Babel that transpiles your ES6 code to ES5.

Share:
14,720
Arkadiy Stepanov
Author by

Arkadiy Stepanov

Updated on June 04, 2022

Comments

  • Arkadiy Stepanov
    Arkadiy Stepanov almost 2 years

    I have a custom.js file with jquery code :

    $('.nav.navbar-nav > li').on('click', function(e) {
    $('.nav.navbar-nav > li').removeClass('active');
    $(this).addClass('active');
    });
    

    I want to export this code to the main.js file.Both files are in the same folder.

    Went through the documentation but couldn't understand how to do it with jquery.

  • Arkadiy Stepanov
    Arkadiy Stepanov over 7 years
    browserify and babel will do the job?
  • Alon
    Alon over 7 years
    @ArkadiyStepanov yes they will!
  • Arkadiy Stepanov
    Arkadiy Stepanov over 7 years
    i have found this example while reading the documentations about browserify var fs = require("fs"); var browserify = require("browserify"); browserify("./script.js") .transform("babelify", {presets: ["es2015", "react"]}) .bundle() .pipe(fs.createWriteStream("bundle.js")); but i cannot seem to implement it to my task gulp.task('app-scripts', function() { return gulp.src('src/js/app.js') .pipe(babel({ presets: ["es2015"] })) .pipe(uglify()) .pipe(gulp.dest('build/js')); }); Do you have any source that will help me?
  • Arkadiy Stepanov
    Arkadiy Stepanov over 7 years
    i have already checked it,but it has a lot of things that i dont need,for example watchify = require('watchify'), i am limited only using babelify,babel,browserify and vinyl plugins,
  • Alon
    Alon over 7 years
    @ArkadiyStepanov consider using Webpack instead of browserify. It's more complicated but you will find a lot more examples on it combined with Babel