问题
I want to use a dependency management in application and came across require.js and browserify . i am unable to decide which one to go with.
It would be a decicive factor if any one can tell me how i can include custom made javascript modules (non node modules) into my js. I see browserify is including node modules with ease.
回答1:
Let's say we want to encapsulate following functionality into module:
sayHelloInEnglish = function() {
return "Hello";
};
Then we create file greetings.js like that:
module.exports = {
sayHelloInEnglish: function() {
return "Hello";
}
};
Then we want to use greetings module in another module, eg. in our main.js file:
var greetings = require("./greetings.js");
greetings.sayHelloInEnglish();
That's how we declare dependencies.
Apart from that we need a building process as well, so our JS code could run inside browser. For that I've chosen gulp.js streaming build system. Then all you need is to create one task like this:
gulp.task('browserify', function () {
gulp.src('main.js')
.pipe(browserify())
.pipe(concat('main.js'))
.pipe(gulp.dest('dist/js'));
});
This task will load all dependencies of main.js, include them before the main.js body and then it will save altogether as a new file into 'dist/js', or any destination you will choose.
回答2:
You can include your custom made javascript modules using current command (this is saving your module into the new variable):
greatestModuleEver = require('./your_module.js');
来源:https://stackoverflow.com/questions/29118749/how-to-include-non-node-modules-using-browserify