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();
Also notice that you need a module loader (like webpack/systemjs/requirejs etc.), as well as Babel that transpiles your ES6 code to ES5.
Author by
Arkadiy Stepanov
Updated on June 04, 2022Comments
-
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 over 7 yearsbrowserify and babel will do the job?
-
Alon over 7 years@ArkadiyStepanov yes they will!
-
Arkadiy Stepanov over 7 yearsi 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 taskgulp.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 over 7 yearsi 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 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