Reputation: 9649
I am using Gulp and Browserify to build a TypeScript librariy which depends on some other libraries like for example jQuery via NPM. This is my current gulpfile:
var Gulp = require("gulp");
var Browserify = require("browserify");
var Buffer = require("vinyl-buffer");
var Rename = require("gulp-rename");
var Source = require("vinyl-source-stream");
var Tsify = require("tsify");
var Uglify = require("gulp-uglify");
var Manifest = require("./package.json");
Gulp.task("build-Debug", function () {
return Browserify({
debug: true,
standalone: Manifest.name
})
.add(Manifest.main)
.plugin(Tsify)
.bundle()
.on("error", function (error) { console.error(error.toString()); })
.pipe(Source(Manifest.name + ".js"))
.pipe(Buffer())
.pipe(Gulp.dest("./dist"));
});
The bundled JS-File gets included in my site and everything works fine. I am just missing one thing: on some sites, I need to define some custom JS which shouldn't get part of the library. These custom script should be able to use jQuery for instance, but it can't since it isn't accessible from outside of the bundle.
Now, I could include it again, but this does not make sense to me. So i'd like to know:
Is there a way to make all of my dependecies from package.json
accessible from outside the bundle, so that I would be able to call
$("#my_id")....
in my custom client-scripts?
Upvotes: 0
Views: 86
Reputation: 58400
You can use Browserify's require
method to expose modules as external requires:
return Browserify({
debug: true,
standalone: Manifest.name
})
.add(Manifest.main)
.require("some-module") // Some module in node_modules that you want to expose.
.plugin(Tsify)
.bundle()
...
You'd obtain the module in a <script>
element like this:
<script>
var someModule = require("some-module");
/* ... */
</script>
To verify that this does in fact work, you could test it with the following files:
build.js
const browserify = require("browserify");
const path = require("path");
browserify("app.js")
.require("jquery")
.bundle()
.pipe(process.stdout);
app.js
const jquery = require("jquery");
console.log("Hello, world.")
index.html
<!doctype html>
<html>
<head>
<title>so-41095676</title>
</head>
<body>
<script src="./bundle.js"></script>
<script>
console.log(require("jquery"));
</script>
</body>
</html>
Create the files in a directory and run these commands:
npm install browserify jquery
node build.js > bundle.js
Then open index.html
and you should see the jQuery function logged to the console.
Upvotes: 1