Reputation: 1943
So I'm writing a php-package which will be put on github&packagist. It generates and writes data to a file, and the package will also come with a js-library which job is to read that data-file and display it to the user. Now, this js-library depends on other libraries, jquery being one among a couple others.
What would be a clean way of declaring those dependencies?
I don't mind using require.js and I have in fact used it for several other projects. But those projects have been complete "apps", not libraries that others are to include in their projects. So in those cases it was no concern adding dependencies and configuring require.js, and it only had to be done once. But this time I want to be able to include this library with minimal amount of code, preferbly without long instructions on how to load it correctly and what other libraries the developer would need to load in as well.
In short: I want to distribute a library that depends on other libraries, which me or another developer can include in another project with minimal amount of code and without knowledge of what other libraries this one depends on.
I'm sure this has been asked before, but I can't seem to find anything on it. I do find lot of information on how to declare dependencies in main projects, but not in libraries.
Upvotes: 0
Views: 734
Reputation: 24941
You have two options:
In both cases you will need to create an automated build. You can use gulp to create tasks to concatenate all your files into a single file like framework.js
and framework.min.js
files that other developers will import.
You can use If you are using require.js you could use the gulp-requirejs plugin to run the requirejs optimizer:
var gulp = require('gulp'),
rjs = require('gulp-requirejs');
gulp.task('requirejsBuild', function() {
rjs({
baseUrl: 'path/to/your/base/file.js',
out: 'FILENAME\_TO\_BE\_OUTPUTTED',
shim: {
// standard require.js shim options
},
// ... more require.js options
})
.pipe(gulp.dest('./delpoy/')); // pipe it to the output DIR
});
If you decide to include the 3th party libraries as well, use the No conflict fucntion to avoid problems if somebody has already loaded jquery.
If you decide to don't include the libraries you can look for some variables in the global scope in your library and throw errors if the dependencies are not available.
if(typeof $ === "undefined") throw new Error("Framework requires > Jquery 1.9.0");
You can usually find the version of a library with ease, for example in jquery:
$.prototype.jquery
I would personally recommend to use Browserify. If you are using requirejs, you can use browserify-ftw to automatically migrate your project from AMD to CommonJS.
The Browserify optimizer will generate a bundle.js
file that your users will be able to import directly without having to download 3th party dependencies or configuring a module loader.
Hope it helps :)
Upvotes: 1