惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cloudbric
Cloudbric
T
Threat Research - Cisco Blogs
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog
P
Privacy & Cybersecurity Law Blog
H
Help Net Security
云风的 BLOG
云风的 BLOG
G
GRAHAM CLULEY
Spread Privacy
Spread Privacy
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
Arctic Wolf
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
P
Privacy International News Feed
Blog — PlanetScale
Blog — PlanetScale
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence
The Register - Security
The Register - Security
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
PCI Perspectives
PCI Perspectives
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
A
About on SuperTechFans
W
WeLiveSecurity
GbyAI
GbyAI
V
Vulnerabilities – Threatpost
The GitHub Blog
The GitHub Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Check Point Blog
Y
Y Combinator Blog
月光博客
月光博客
Scott Helme
Scott Helme
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
U
Unit 42
G
Google Developers Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Threatpost
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Google Online Security Blog
Google Online Security Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cisco Talos Blog
Cisco Talos Blog
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 司徒正美

oida.dev | TypeScript, Rust

TypeScript's `erasableSyntaxOnly` Flag Unsafe for work Tokio: Macros Tokio: Channels Tokio: Getting Started Network Applications on the Tokio Stack Remake, Remodel, Reduce. The `never` type and error handling in TypeScript 5 Inconvenient Truths about TypeScript Refactoring in Rust: Introducing Traits Refactoring in Rust: Abstraction with the Newtype Pattern Announcing the TypeScript Cookbook TypeScript: Iterating over objects The road to universal JavaScript 10 years of oida.dev Rust: Tiny little traits The TypeScript converging point How not to learn TypeScript Getting started with Rust Introducing Slides and Coverage TypeScript: The humble function overload TypeScript + React: Children types are broken TypeScript: In defense of any Rust: Enums to wrap multiple errors Dissecting Deno Error handling in Rust TypeScript: Unexpected intersections Upgrading Node.js dependencies after a yarn audit TypeScript: Array.includes on narrow types TypeScript + React: Typing Generic forwardRefs shared, util, core: Schroedinger's module names Learning Rust and Go TypeScript: Narrow types in catch clauses TypeScript: Low maintenance types Tidy TypeScript: Name your generics Tidy TypeScript: Avoid traditional OOP patterns Tidy TypeScript: Prefer type aliases over interfaces Tidy TypeScript: Prefer union types over enums My new book: TypeScript in 50 Lessons Go Preact! ❤️ this in JavaScript and TypeScript TypeScript and ECMAScript Modules TypeScript + React: Why I don't use React.FC TypeScript + React: Component patterns TypeScript: Augmenting global and lib.dom.d.ts Vite with Preact and TypeScript TypeScript: Union to intersection type 11ty: Generate Twitter cards automatically Are large node module dependencies an issue? TypeScript: Variadic Tuple Types Preview TypeScript: Improving Object.keys Remake, Remodel. Part 4. TypeScript + React: Typing custom hooks with tuple types TypeScript: Assertion signatures and Object.defineProperty TypeScript: Check for object properties and narrow down type Boolean in JavaScript and TypeScript void in JavaScript and TypeScript Symbols in JavaScript and TypeScript Why I use TypeScript TypeScript + React: Extending JSX Elements TypeScript: Validate mapped types and const context TypeScript: Match the exact object shape TypeScript: The constructor interface pattern Streaming your Meetup - Part 4: Directing and Streaming with OBS Streaming your Meetup - Part 3: Speaker audio Streaming your Meetup - Part 2: Speaker video Streaming your Meetup - Part 1: Basics and Projector TypeScript and React Guide: Added a new styles chapter TypeScript and React Guide: Added a new render props chapter TypeScript and React: Styles and CSS TypeScript and React TypeScript and React Guide: Added a new prop types chapter TypeScript without TypeScript -- JSDoc superpowers TypeScript: Mapped types for type maps JAMStack vs serverless web apps The Unsung Benefits of JAMStack Sites TypeScript: Ambient modules for Webpack loaders My most favourite talks in 2018 TypeScript and React Guide: Added a new context chapter TypeScript: Built-in generic types TypeScript: Type predicates JSX is syntactic sugar TypeScript and React Guide: Added a new hooks chapter Getting your CfP application right FAQ on our Angular Connect Talk: Automating UI development TypeScript and Substitutability Debugging Node.js apps in TypeScript with Visual Studio Code From Medium: Deconfusing Pre- and Post-processing From Medium: PostCSS misconceptions Saving and scraping a website with Puppeteer Cutting the mustard - 2018 edition Wordpress as CMS for your JAMStack sites My most favourite podcast episodes in 2017 My most favourite talks in 2017 My most favourite books in 2017 The Best Request Is No Request, Revisited Not so hidden figures - Organizing ScriptConf My podcast journey to ScriptCast Grid layout, grid layout everywhere! #scriptconf and #devone
Gulp: Creating multiple bundles with Browserify
2015-03-25 · via oida.dev | TypeScript, Rust

With the ever-changing eco system of Node.js tools, a short version disclaimer. This article has been created using

  • Gulp v3.8
  • Browserify
  • Glob 5.0
  • Event Stream 3.3
  • Vinyl Source Stream 1.1

If something does not work when you’re using the same tutorial, please check if there’s been a major update causing breaking changes. And please do inform me, I like keeping those tutorials updated when possible.

Everything’s a stream #

So what’s the gist? Browserify is a JavaScript bundling tool, which allows you to declare modules in the Node way, but subsequently bundled to work in the browser. Think Require.js, but leaner and in the need of a processing step. Gulp is a build system which is fast, controllable and a good way of processing things. Both use streams. So why not combine them and process Browserify with Gulp?

Good idea in general, but as it turns out both tools handle streams a little differently. Or let’s say: Their contents. While Browserify takes the contents of the files you handle to it, Gulp needs both contents and the original file information, for writing the results afterwards on the hard disk. That’s why it uses Vinyl as a virtual file system. Vinyl objects are streamable, but contain the information of there original origin. So when writing gulp.src('*.js'), you get a bunch of vinyl objects with each representing the original JavaScript file on your disk. gulp.dest('somewhere') just takes a folder where you put your files, how they’re called is still contained in the vinyl object.

Browserify on the other hand forgets about the origin as soon as you start. To make both tools compatible, there was originally a wrapper plugin for browserify called gulp-browserify. But since that was just a wrapper, and Gulp encouraging people to use the original in favour of some non-maintained plugin, they decided to blacklist gulp-browserify and promote the use of wrappers directly.

This is where vinyl-source-stream comes in. It does exactly what gulp-browserify did, but is of course more flexible: It converts any stream to a vinyl object, suitable for the use with Gulp.

One bundle #

So here’s how you handle one Browserify bundle with Gulp

var gulp       = require('gulp'),
browserify = require('browserify'),
source = require('vinyl-source-stream');

gulp.task('browserify', function() {
return browserify({ entries: ['path/to/main.js'] })
.bundle()
.pipe(source('main.bundled.js'))
.pipe(gulp.dest('dist'));
});

We take one file into Browserify, bundle it (that’s the thing Browserify should do), and pipe this stream to the next task, which is creating a vinyl object. Note the parameter, it adds the missing information – the filename – to the stream which comes out of Browserify. Now we can store it.

More bundles #

So far, so good. But there’s a new problem (wouldn’t be fun without one, would it). Once you call bundle, all file information is lost. What you get is one stream representing one file. So if you want to create multiple bundles, you’re pretty lost. This problem seems to occur a lot, just over this weekend, I stumbled upon three different requests on that topic from various sources.

What can you do? Of course you think: Well, if I need it for more than one bundle, than I should run it more than once. That’s absolutely correct, for every bundle you have, you have to run this task. However, we would get in a sequential and non flexible hell nobody wants to be. After all we’re using Gulp, it’s made to run things with maximum efficiency.

What we need are so called stream arrays. Define your stream, create an array of multiple streams, and execute all of them at once:

'use strict';

var gulp = require('gulp'),
source = require('vinyl-source-stream'),
rename = require('gulp-rename'),
browserify = require('browserify'),
es = require('event-stream');

gulp.task('default', function() {
// we define our input files, which we want to have
// bundled:
var files = [
'./app/main-a.js',
'./app/main-b.js'
];
// map them to our stream function
var tasks = files.map(function(entry) {
return browserify({ entries: [entry] })
.bundle()
.pipe(source(entry))
// rename them to have "bundle as postfix"
.pipe(rename({
extname: '.bundle.js'
}))
.pipe(gulp.dest('./dist'));
});
// create a merged stream
return es.merge.apply(null, tasks);
});

The original setup is self explaining, but the last line is important: We merge that array to one stream which will be returned from our task. This way, we tell gulp that this stream is the one stream to execute. That it’s an array internally does not bother anymore.

Using Globs #

Globs allow us to use patterns when selecting files. That functionality is in Gulp, but with our first entry point being browserify and the outcome being a stream array, we have to improvise. That’s the way if you want to have all the files starting with main- and ending with js in your stream array:

'use strict';

var gulp = require('gulp'),
source = require('vinyl-source-stream'),
rename = require('gulp-rename'),
browserify = require('browserify'),
glob = require('glob'),
es = require('event-stream');

gulp.task('default', function(done) {
glob('./app/main-**.js', function(err, files) {
if(err) done(err);

var tasks = files.map(function(entry) {
return browserify({ entries: [entry] })
.bundle()
.pipe(source(entry))
.pipe(rename({
extname: '.bundle.js'
}))
.pipe(gulp.dest('./dist'));
});
es.merge(tasks).on('end', done);
})
});

So this one makes it even more flexible.

Bottom line #

One thing I learned when doing this example over and over, was to appreciate and understand streams. That concept seems clear from the get go when you’re starting with Gulp, but in the end it’s much more than that. Gulp’s just a use-case for streams, not a stream implementation. If you can divide streams and virtual file objects (a.k.a vinyl objects), and focus your learnings on the stream part, you realise that you can do wonderful things with it.

Thanks to Simon Dean and Soós Gábor for updates on the last task

Related Articles