browserify_Browserify入门

browserify

Browserify changed my life.

Browserify改变了我的生活。

. . . My life as a Javascript developer, anyway. Unlike many of my peers--maybe most of them--I don't enjoy writing UIs. Hacking together client-side code always felt something like a visit to the dentist. I'm like a hobbit

。 。 。 无论如何,我作为JavaScript开发人员的生活。 与我的许多同龄人(也许是大多数同龄人)不同,我不喜欢编写UI。 一起破解客户端代码总是感觉就像去看牙医一样。 我就像霍比特人

Then Browserify happened. And everything changed.

然后发生了Browserify 。 一切都变了。

With Browserify you can write code [in the browser] that uses require in the same way that you would use it in Node.

借助Browserify,您可以[在浏览器中]编写使用require代码,就像在Node中使用它一样。

Browserify lets you use require in the browser, the same way you'd use it in Node. It's not just syntactic sugar for loading scripts on the client. It's a tool that brings all the resources NPM ecosystem off of the server, and into the client.

Browserify允许您在浏览器中使用require ,就像在Node中使用它一样。 在客户端上加载脚本的不仅仅是语法糖。 它是一种将NPM生态系统的所有资源从服务器带入客户端的工具。

Simple, yet immensely powerful.

简单但功能强大。

In this article, we'll take a look at:

在本文中,我们将看一下:

  • What Browserify is & How it Works

    什么是Browserify及其运作方式
  • Browserify vs Webpack

    Browserify与Webpack
  • Building Your First Bundle

    建立你的第一个捆绑
  • Browserify Transforms

    Browserify转换
  • Building a Useful Browserify Config

    构建有用的Browserify配置
  • Integrating with Gulp

    与Gulp集成

Before we get started, make sure you've got Node and NPM installed. I'm running Node 5.7.0 and NPM v3.6.0, but versioning shouldn't be a problem. Feel free to either grap the repo or code along.

在开始之前,请确保您已经安装了Node和NPM。 我正在运行Node 5.7.0和NPM v3.6.0,但是版本控制应该不是问题。 随意掌握仓库或代码。

Let's dive in.

让我们潜入。

为什么使用Browserify? ( Why Browserify? )

Anyone who's worked with Node will be familiar with its CommonJS style require function.

使用Node的任何人都将熟悉其CommonJS样式的require函数

require-ing a module exposes its public API to the file you required it in:

require -ing模块将其公共API公开给您在以下位置所需的文件:

"use strict";
const React = require('react');

let Component = React.createClass ({
    /* Using React, save the world */
});

Node's require implementation makes modularizing server-side code quite a straightforward task. Install, require, hack: Dead simple.

Node的require实现使模块化服务器端代码变得非常简单。 安装,要求,破解:简简单单。

Module loading in the client is an inherently different beast. In the simplest case, you load your modules in a series of <script> tags in your HTML. This is perfectly correct, but it can be problematic for two reasons:

客户端中的模块加载是天生就不同的野兽。 在最简单的情况下,您可以在HTML中的一系列<script>标记中加载模块。 这是完全正确的,但是由于两个原因可能会出现问题:

  • It forces you to manage dependencies by ensuring your script tags appear in the proper order, and makes it cumbersome to manage complex dependency graphs

    它通过确保脚本标签以正确的顺序显示来迫使您管理依赖关系,并且使管理复杂的依赖关系图变得麻烦
  • To quote Kyle Simpson's in the LAB.js documentation: "with regular <script> tags, you cannot control [script] loading and executing behavior reliably cross-browser."

    LAB.js文档中引用凯尔·辛普森(Kyle Simpson)的 :“使用常规的<script>标记,您将无法跨浏览器可靠地控制[script]加载和执行行为。”

The AMD specification and AMD loaders--Require.js being amongst the most popular--came about as solutions to these issues. And, frankly, they're awesome. There's nothing inherently wrong with Require.js, or AMD loaders in general, but the solutions furnished by newer tools like Browserify and Webpack bring distinct advantages over those offered by Require.js.

AMD规范和AMD加载程序(其中 Require.js 最受欢迎)是这些问题的解决方案。 而且,坦率地说,它们很棒。 一般而言,Require.js或AMD加载程序没有本质上的问题,但较新的工具(例如Browserify和Webpack)提供的解决方案比Require.js提供的解决方案具有明显的优势

Amongst other things, Browserify:

除了其他功能,Browserify还包括:

  • Trivializes many preprocessing tasks with its transform system;

    借助其转换系统将许多预处理任务简化了;
  • Solves the same problems regarding asynchronous loading addressed by Require.js;

    解决由Require.js解决的有关异步加载的相同问题;
  • Opens the doors to the vast and growing NPM ecosystem

    打开广阔的NPM生态系统之门

We'll take a look at all of this and a whole lot more throughout the article. But first, what's the deal with Webpack?

我们将在本文中介绍所有这些内容以及更多内容。 但是首先,与Webpack有何关系?

Browserify与Webpack ( Browserify vs Webpack )

The religious wars between users of Angular and Ember, Grunt and Gulp, Browserify and Webpack, all prove the point: Choosing your development tools is serious business.

Angular和Ember,Grunt和Gulp,Browserify和Webpack的用户之间的宗教战争都证明了这一点:选择开发工具是一件严肃的事

The choice between Browserify or Webpack depends largely on the tooling workflow you already have and the exigencies of your project. There are a number of differences between their feature sets, but the most important distinction, to my mind, is one of intent:

在Browserify或Webpack之间进行选择在很大程度上取决于您已经拥有的工具工作流程和项目的紧急程度。 它们的功能集之间有许多区别,但是我认为最重要的区别是意图之一:

  • Browserify seeks to extend the Node ecosystem into to the browser. It only supports Node's flavor of the CommonJS require syntax, and provides browser-specific shims for much of Node's core functionality.

    Browserify试图将Node生态系统扩展到浏览器中。 它仅支持Node的CommonJS require 语法 ,并为Node的许多核心功能提供了特定于浏览器的填充
  • Webpack seeks to unify Javascript module syntaxes and provide tools for a full swath of static asset management tasks. It imposes no restrictions on your choice of module syntax, and offers full support for Javascript, CSS, and even image preprocessing.

    Webpack寻求统一Javascript模块语法,并提供用于全部静态资产管理任务的工具。 它对您选择的模块语法没有任何限制,并完全支持Javascript,CSS甚至图像预处理。

If your project and dependencies are already closely tied to the Node ecosystem, Browserify is a solid choice. If you need more power to manage static assets than you can shake a script at, Webpack's your tool.

如果您的项目和依赖项已经与Node生态系统紧密相关,则Browserify是一个不错的选择。 如果您需要比静态脚本强大的功能来管理静态资产,那么Webpack就是您的工具。

I tend to stick with Browserify, as I rarely find myself in need of Webpack's additional power. You mind find Webpack to be a solid choice if your build pipeline gets complex enough, though.

我倾向于坚持使用Browserify,因为我很少发现自己需要Webpack的其他功能。 但是,如果您的构建管道变得足够复杂,您会发现Webpack是一个不错的选择。

If you decide to check it out, take a look at Front-End Tooling Book's chapter on Webpack, and Pete Hunt's Webpack How-To before diving into the official docs.

如果您决定进行检查, 请先阅读Webpack上的《 前端工具手册》中的章节以及Pete Hunt的Webpack How-To,然后再阅读正式文档。

使用Browserify构建您的第一个捆绑软件 ( Build Your First Bundle with Browserify )

Note: If you don't feel like typing or copy/pasting, clone my repo.

注意:如果您不想打字或复制/粘贴,请克隆我的仓库

Time to get our hands dirty. The first step is to install Browserify. Fire up a terminal and run:

是时候弄脏我们的双手了。 第一步是安装Browserify。 启动终端并运行:

npm install --global browserify

npm install --global browserify

This installs the Browserify package, and makes it available system-wide.

这将安装Browserify软件包,并使它在系统范围内可用。

Oh, and if you find yourself needing to use sudo for this, fix your NPM permissions.

哦,如果您发现需要使用sudo ,请修复NPM权限

Next, let's give our little project a home. Find a suitable place on your hard drive and make a new folder for it:

接下来,让我们给我们的小项目一个家。 在硬盘上找到合适的位置,并为其新建一个文件夹:

mkdir Browserify_Introduction && cd Browserify_Introduction

mkdir Browserify_Introduction && cd Browserify_Introduction

We'll need a minimal home page, as well. Drop this into index.html:

我们还需要一个最小的主页。 将其放入index.html

<!-- index.html -->
<!doctype html>
<html>
  <head>
    <title>Getting Cozy with Browserify</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <style>
      h1, p, div { text-align: center; }
      html       { background: #fffffe; }
    </style>
  </head>
  <body>
    <div class="container">
      <h2>Welcome to the Client Side.</h2>

      <div class="well">
        <p>I see you've got some numbers. Why not let me see them?</p>

        <div id="response">
        </div>
      </div>
    </div>
    <script src="main.js"></script>
    <script src="bundle.js"></script>
  </body>
</html>

In the off chance you're typing this out by hand, you'll definitely have noticed the reference to the nonexistent main.js. Nonexistent files are no fun, so let's make it exist.

在您手动输入时,肯定会注意到对不存在的main.js的引用。 不存在的文件不好玩,所以让它存在。

First, install Ramda:

首先,安装Ramda

npm install ramda --save

npm install ramda --save

There's nothing special about Ramda, by the way. I just chose it because I like it. Any package would do.

顺便说一句,Ramda没什么特别的。 我选择它是因为我喜欢它。 任何包装都可以。

Now, drop this into main.js:

现在,将其放入main.js

main.js
"use strict";

var R = require('ramda');

var square = function square (x) { return x * x; }  
var squares = R.chain(square, [1, 2, 3, 4, 5]); 

document.getElementById('response').innerHTML = squares;

This is simple, but let's go step-by-step anyway.

这很简单,但是我们还是要逐步进行。

  • Line 3 requires the Rambda library as R;

    第3行要求Rambda库为R;
  • Line 5 defines a simple function for us to use in our example;

    第5行定义了一个简单的函数供我们在示例中使用;
  • Line 6 uses Rambda to do some stuff, and assign the result to squares;

    第6行使用Rambda进行处理,并将结果分配给squares
  • Line 8 finds the div on our page with the id response, and sets its innerHTML to squares

    第8行在页面上找到带有id responsediv ,并将其innerHTML设置为squares

The important things to note are that we're using Node's require, available only in a Node environment, together with the DOM API, available only in the browser.

需要注意的重要事情是, 我们使用的Node的require (仅在Node环境中可用) 和DOM API一起 ,仅在浏览器中可用。

That shouldn't work. And, in fact, it doesn't. If you open index.html in your browser and open up the console, you'll find a ReferenceError just waiting to grab your attention.

那不行 而且,实际上并非如此。 如果在浏览器中打开index.html并打开控制台,则会发现ReferenceError只是在引起您的注意。

Reference Error

Ew. Let's get rid of that.

w 让我们摆脱它。

In the same directory housing your main.js, run:

在包含main.js的同一目录中,运行:

browserify main.js -o bundle.js

browserify main.js -o bundle.js

Now open up index.html again, and you should see our array of squares smack dab in the middle of the page.

现在,再次打开index.html ,您应该在页面中间看到我们的正方形数组点击DAB。

It's that simple.

就这么简单。

引擎盖下 ( Under the Hood )

When you tell Browserify to bundle up main.js, it scans the file, and takes note of all the files you require. It then includes the source of those files in the bundle, and repeats the process for its dependencies.

当您告诉Browserify捆绑main.js ,它将扫描文件,并记录您require的所有文件。 然后,它将这些文件的源包含在捆绑软件中,并对其依赖项重复该过程。

In other words, Browserify traverses the dependency graph, using your main.js as its entry point, and includes the source of every dependency it finds.

换句话说,Browserify使用main.js作为入口点遍历依赖关系图,并包括找到的每个依赖关系的来源。

If you open up your bundle.js, you'll see this in action. At the top is some obfuscated weirdness; then, a portion with your source code; and finally, the entirety of the Ramda library.

如果打开bundle.js ,您将看到实际的效果。 顶部是一些模糊的怪异; 然后,一部分包含您的源代码; 最后是整个Ramda库。

Your Bundle

Magic, eh?

魔术,是吗?

Let's take a look at some additional Browserify fundamentals.

让我们看一下其他一些Browserify基础知识。

Browserify转换 ( Browserify Transforms )

Browserify isn't limited to concatenating the source of your dependencies: It's also capable of transforming the code along the way.

Browserify不仅限于连接依赖项的来源:它还可以一路转换代码。

"Transform" can mean many things. It can be compiling Coffeescript to Javascript, transpiling ES2015 to vanilla Javascript, or even replacing const with var declarations.

“转换”可能意味着很多事情。 它可以将Coffeescript编译为Javascript ,将ES2015转换为原始Javascript ,甚至可以用var声明替换const

If it's a change to your code, it counts as a transformation. We'll take a look at using transforms in the full example, so hang on tight for usage details. For now, be sure to bookmark the growing list of available Browserify transforms for future reference.

如果是对代码的更改,则视为转换。 我们将在整个示例中看一下使用转换,因此请耐心等待使用细节。 现在,请确保将不断增长的可用Browserify转换列表添加书签,以备将来参考。

启用源地图 ( Enabling Source Maps )

One of the disadvantages to transformations--and builds in general--is mangled line references. When your code throws an error, you want the browser to tell you, take a look at line 57, column 23. Not, take a look at variable q on line 1, column 18,278 of main.min.js.

转换的缺点(通常是构建)的缺点之一是折线引用。 当代码抛出错误时,您希望浏览器告诉您, 请看一下第57行第23列 。 不, 请看main.min.js的第1行第18,278列中的变量q。

The solution is source maps. They're files that tell your browser how to translate between line references in your transformed code and line references in your original source.

解决方案是源地图 。 它们是文件,它们告诉您的浏览器如何在转换后的代码中的行引用和原始源中的行引用之间进行转换。

With Browserify, enabling source maps is trivial. Run:

使用Browserify,启用源地图非常简单。 跑:

browserify --debug main.js -o bundle.js

browserify --debug main.js -o bundle.js

The --debug flag tells Browserify to include source map information in bundle.js. That's all you have to add to make it work.

--debug标志告诉Browserify包括源地图信息bundle.js 。 这就是您要做的所有添加。

There is one downside to this, though: Adding source maps to bundle.js makes your bundle twice as large.

但是,这样做有一个缺点: 将源映射添加到bundle.js会使您的bundle bundle.js两倍

That's fine for development. But making your users download a file twice as big as the one they really need is a bit rude, don't you think?

这对发展很好。 但是让用户下载的文件比他们真正需要的文件大两倍是不礼貌的,不是吗?

The solution is to create two files: One for the source map, one for the bundle. If you're using Browserify alone, the tool of choice for this is exorcist.

解决方案是创建两个文件:一个用于源映射,一个用于分发包。 如果你只使用Browserify,选择这个工具是驱魔

Once you've installed it (npm install --global exorcist), you use it like this:

一旦安装了它( npm install --global exorcist ),就可以像这样使用它:

browserify main.js --debug | exorcist bundle.map.js > bundle.js

browserify main.js --debug | exorcist bundle.map.js > bundle.js

This rips all the source map information out of bundle.js and spits it into bundle.map.js instead.

bundle.js所有源地图信息从bundle.js出来, bundle.js其吐到bundle.map.js

That's mostly all there is to using exorcist. Be sure to check the exorcist documentation for the details.

使用驱魔人几乎就是所有这些。 请务必查看驱魔人文档以获取详细信息。

现场重建 ( Live Rebuild )

I'll admit, it kind of sucks to have to drop out of your editor and into the CLI to rebuild your bundle every time you change your code.

我承认,每次更改代码时,都必须退出编辑器并进入CLI来重新构建捆绑包,这真是太糟糕了。

. . . Good thing you don't have to.

。 。 。 好东西,你不必。

There are a whole swath of tools for Browserify that keep an eye on your files and rebuild your bundle whenever they change. We'll take a look at two tools: Watchify, and Beefy.

有大量的Browserify工具可用于监视文件并在文件更改时重新构建捆绑包。 我们将看一下两个工具: WatchifyBeefy

使用Watchify (Using Watchify)

Watchify is a standard tool for automatically rebuilding your bundle.js whenever you update source files.

Watchify是一个标准工具,用于在您更新源文件时自动重建bundle.js

First, install it with NPM:

首先,使用NPM安装它:

npm install --global watchify

npm install --global watchify

Next, delete your bundle.js.

接下来,删除您的bundle.js

Now, navigate to your working directory in a new terminal, and run:

现在,在新终端中导航到您的工作目录,然后运行:

watchify main.js -o bundle.js -v

watchify main.js -o bundle.js -v

The -v flag tells Watchify to notify you whenever it rebuilds your bundle. It'll still work if you don't include it, but you won't be able to tell it's doing anything.

-v标志告诉Watchify每当它重建您的捆绑软件时通知您。 如果您不包含它,它将仍然有效,但是您将无法判断它在做什么。

That aside, notice that using watchify is identical to using Browserify! You should have gotten some output, and if you check, you'll notice a newly updated bundle.js sitting in your working directory.

除此之外,请注意,使用watchify 使用Browserify 相同 ! 您应该已经获得了一些输出,如果进行检查,您会注意到工作目录中有一个新更新的bundle.js

Now, open up main.js and save it without changing anything. You'll see Watchify rebuild your bundle and spit out some more logs--that's all it takes to automatically rebuild your bundle when you change your source!

现在,打开main.js并保存而不更改任何内容。 您会看到Watchify重建了您的捆绑包并吐出了更多日志-这就是您在更改来源时自动重建捆绑包的全部内容!

The Watchify repo has all the information on more advanced usage, such as how to use it with exorcist. Check them out if you need.

Watchify存储库包含有关更高级用法的所有信息,例如如何与驱魔人一起使用。 如果需要,请查看它们。

If you ran the example, be sure to kill the Watchify process before moving on (just close the terminal you ran it in, or kill $(pgrep node) if you love you some CLI).

如果运行了示例,请确保在继续之前终止Watchify进程(只需关闭运行它的终端,或者,如果您喜欢某些CLI,则终止kill $(pgrep node) )。

(Beefy)

While it's cool that we can automatically rebuild our bundle when we change our source, it still kind of sucks to have to refresh the browser every time we want to see the changes.

虽然在更改源代码时可以自动重建捆绑包很酷,但是每次我们要查看更改时都必须刷​​新浏览器仍然很麻烦。

Or maybe I'm just especially lazy.

也许我只是特别懒惰。

Either way, Beefy makes it easy to enable live reload alongside automatic rebuild. It does two big things for you:

无论哪种方式, Beefy都可以轻松实现实时重新加载以及自动重新构建 。 它为您做两件事:

  • Spin up a local webserver that serves your files;

    启动一个本地网络服务器来提供文件;
  • Start a process to watch your filesystem for changes to your source code.

    启动一个过程来监视文件系统中源代码的更改。

Whenever you change anything, it rebuilds your bundle, and--if you tell it to--automatically refreshes your browser with the changes.

每当您更改任何内容时,它都会重建您的捆绑软件,并且-如果您告诉您-会自动通过更改刷新浏览器。

If you're like me and need such a minimal feedback loop, it's hard to go wrong with Beefy.

如果您像我一样,并且需要这样一个最小的反馈回路,那么Beefy很难出错。

To get started, go ahead and install it:

首先,请安装它:

npm install -g beefy

npm install -g beefy

I've installed it globally because I use it so much. If you'd rather use it on a per-project basis, run:

我已经在全球安装了它,因为我经常使用它。 如果您希望在每个项目中使用它,请运行:

npm install --save-dev beefy

npm install --save-dev beefy

Either way, using it is straightforward. First, delete your bundle.js. Then, Spin up a new terminal, navigate to your working directory, and run:

无论哪种方式,使用它都非常简单。 首先,删除您的bundle.js 。 然后,启动一个新终端,导航到您的工作目录,然后运行:

beefy main.js --live

beefy main.js --live

Beefy should print some information notifying you that it's listening on http://127.0.0.1:9966.

Beefy应该在http://127.0.0.1:9966上打印一些信息,通知您正在监听。

If instead it says, Error: Could not find a suitable bundler!, run this instead:

如果相反,则显示错误:错误:找不到合适的捆绑器! ,请改为运行:

beefy main.js --browserify $(which browserify) --live

beefy main.js --browserify $(which browserify) --live

The --browserify $(which browserify) bit tells Beefy to use the global Browserify installation. You don't need this unless you got the error.

--browserify $(which browserify)位告诉Beefy使用全局Browserify安装。 除非出现错误,否则不需要此功能。

We told Beefy to watch main.js. If your entry point has a different name--say, app.js--you'd pass it that instead. The --live switch tells Beefy to automatically rebuild your bundle and reload the browser whenever you change your source code.

我们告诉Beefy看main.js 如果您的入口点具有其他名称(例如, app.js则可以通过它。 --live开关告诉Beefy每当您更改源代码时就自动重建软件包重新加载浏览器。

Let's see it in action. In your browser, navigate to http://localhost:9966. You should see the same home page we did last time.

让我们来看看它的作用。 在浏览器中,导航到http://localhost:9966 。 您应该看到与上次相同的主页。

Our Initial Web Page

Now, open up main.js, and change squares:

现在,打开main.js ,并更改squares

"use strict";

var R = require('ramda');

var square = function square (x) { return x * x; }  
var squares = R.chain(square, [1, 2, 3, 4, 5, 6]); 

document.getElementById('response').innerHTML = squares

Save it, and check out the web page. You should see an updated version of it:

保存它,然后检出网页。 您应该看到它的更新版本:

Our Web Page After Update

And if you were watching it as you saved, you'd have noticed it update in real time.

而且,如果您在保存时观看它,您会发现它是实时更新的。

Under the hood, Beefy rebuilds your main.js whenever the server receives a request for bundle.js. Beefy does not save a bundle.js to your working directory; when you need one for production, you'll still have to build that using Browserify. We'll see how to deal with that inconvenience in just a second.

在后台, main.js每当服务器接收到bundle.js的请求时,就会重新main.js bundle.js保存bundle.js到您的工作目录; 当您需要一个用于生产时,您仍然必须使用Browserify进行构建。 我们将在一秒钟内看到如何处理这种不便。

Again, that's all there is to it. If you need anything more specific, the documentation's got your back.

再说一遍,仅此而已。 如果您需要更具体的信息,则可以继续使用该文档

建立基本的Browserify配置 ( Building a Basic Browserify Configuration )

That's it for Browserify: The Essentials. Let's build a small Browserify configuration that:

就可以使用Browserify:The Essentials 。 让我们构建一个小的Browserify配置:

  • Lets us include either Javascript or Coffeescript dependencies;

    让我们包括Javascript或Coffeescript依赖项;
  • Displays updates in the client in real time via live reload;

    通过实时重新加载实时显示客户端中的更新;
  • Outputs a minified bundle.js with separate sourcemaps when we build manually.

    手动构建时,输出带有单独源映射的缩小的bundle.js

A real, production-quality workflow would do more. But this will show you how to use Browserify to do something nontrivial, and extending it for your own projects should be a cinch.

真正的,具有生产质量的工作流程会做更多的事情。 但这将向您展示如何使用Browserify来完成一些琐碎的事情,并且将其扩展到自己的项目中应该是一件容易的事。

We'll be using NPM scripts to set this up. In the next section, we'll do it with Gulp.

我们将使用NPM脚本进行设置。 在下一节中,我们将使用Gulp进行操作。

Let's get to it.

让我们开始吧。

安装依赖项 (Installing Dependencies)

We'll need to install some packages to get this done:

我们需要安装一些软件包才能完成此操作:

  • Caching-Coffeify, for Coffeescript support while the server is running;

    Caching-Coffeify ,在服务器运行时提供Coffeescript支持;
  • Coffeeify, for Coffeescript support when we build our output bundle;

    Coffeeify ,在构建输出包时获得Coffeescript支持;
  • Beefy, for live reload;

    健壮 ,用于实时重新加载;
  • Minifyify, for minfiying our bundle.

    Minifyify ,用于缩小我们的捆绑包。

You've already got Beefy, so don't worry about installing it. To grab the others, run:

您已经拥有Beefy,因此不必担心安装它。 要获取其他对象,请运行:

npm install --save-dev caching-coffeeify coffeeify minifyify

npm install --save-dev caching-coffeeify coffeeify minifyify

Now, let's start building out our scripts. Open up your package.json. You should find a scripts key about halfway down; it should include a key called "tests".

现在,让我们开始构建脚本。 打开您的package.json 。 您应该在大约一半的位置找到一个scripts键。 它应该包含一个称为“测试”的键。

Right after it, add a "serve" task:

在此之后,添加一个“服务”任务:

"serve" : "beefy main.js --live"

"serve" : "beefy main.js --live"

You can see the whole package.json at my GitHub repo. If you had to use the --browserify $(which browserify) option earlier, you'll have to do that here to.

您可以在我的GitHub存储库中看到整个package.json 。 如果您必须更早使用--browserify $(which browserify)选项,则必须在此处执行此操作。

Save that, and back in your terminal, run npm run serve. You should see the same output we got when we ran Beefy earlier.

保存该内容,然后在终端中运行npm run serve 。 您应该看到我们之前运行Beefy时获得的相同输出。

You may get an ENOSPC error. If you do, run npm dedupe and try again. If that doesn't help, the top answer on this SO thread will solve the problem.

您可能会收到ENOSPC错误。 如果这样做,请运行npm dedupe然后重试。 如果这样做没有帮助, 那么此SO线程的最佳答案将解决此问题

We just associated a command--beefy main.js --live--with a script name--serve. When we run npm run <NAME>, NPM executes the command associated with the name you pass, located in the "scripts" section of your package.json. In this case, np run serve fires up Beefy.

我们只是相关的command-- beefy main.js --live --with脚本名称- serve 。 当我们运行npm run <NAME> ,NPM执行与您传递的名称相关联的命令,该命令位于package.json的“ scripts”部分。 在这种情况下, np run serve打发Beefy。

Sweet start. Let's finish it up.

美好的开始。 让我们结束它。

Open up package.json again, and add to your serve script:

再次打开package.json ,然后将其添加到serve脚本中:

"serve" : "beefy main.js --browserify -t caching-coffeeify --live"

"serve" : "beefy main.js --browserify -t caching-coffeeify --live"

When using Beefy, the --browserify option lets you pass options to Browserify. The -t flag tells Browserify you're about to give it a transform to run. Caching-Coffeeify is a transform that compiles Coffeescript to Javascript, and optimizes to make sure it only recompiles what's changed--whenever you want to compile Coffeescript on-the-fly like this, Caching-Coffeeify is a better choice than plain ol' Coffeeify.

使用Beefy时,使用--browserify选项可将选项传递给Browserify。 -t标志告诉Browserify您即将对其进行转换。 Caching-Coffeeify是一种将Coffeescript编译为Javascript并进行优化以确保仅重新编译更改的转换-每当您想要像这样即时编译Coffeescript时,Caching-Coffeeify都是比普通的Coffeeify更好的选择。

Now, we can include Coffeescript files in our project. To see this in action, create list_provider.coffee alongside your main.js:

现在,我们可以在项目中包含Coffeescript文件。 要查看实际效果,请在main.js旁边创建list_provider.coffee

# list_provider.coffee
"use strict"
module.exports = () => [1, 2, 3, 4, 5]

. . . And in main.js:

。 。 。 在main.js中:

// main.js
"use strict";

var R = require('ramda'),
      get_list = require('./list_provider.coffee');

var square = function square (x) { return x * x; }  
var squares = R.chain(square, get_list()); 

document.getElementById('response').innerHTML = squares

Now, run npm run serve, navigate to http://localhost:9966, and everything should still work.

现在,运行npm run serve ,导航到http:// localhost:9966 ,一切仍然应该正常。

构建任务 (A Build Task)

To add a script that build outs a minified bundle with stripped source maps, open up your package.json and add:

要添加一个脚本,该脚本用剥离的源地图构建一个缩小的捆绑包,请打开您的package.json并添加:

/* Remainder omitted */

"serve"         : "beefy main.js --browserify -t caching-coffeeify --live",
"build" : "browserify main.js --debug -t coffeeify -t -p [ minifyify --map bundle.js.map --output build/bundle.map.js ] > build/bundle.js" 

/* Remainder omitted */

Now, in your working directory, run mkdir build. This is the folder we'll save our bundle.js and sourcemap too. Run npm run build; check what's in your build folder; and voilà.

现在,在您的工作目录中,运行mkdir build 。 这是我们bundle.js保存bundle.js和sourcemap的文件夹。 运行npm run build ; 检查您的构建文件夹中的内容; 和voilà

Your Build Folder

用Gulp设置 ( Setting Up with Gulp )

I assume you're already familiar with Gulp. If not, check out the docs.

我认为您已经熟悉Gulp。 如果没有, 请检查docs

Using NPM scripts is fine for simple setups. But it's already clear that this can get cumbersome and unreadable.

使用NPM脚本适合简单的设置。 但是已经很清楚,这可能变得麻烦且难以理解。

That's where Gulp comes in.

那就是Gulp进来的地方。

In the interest of brevity, we'll just set up a basic task that does the following:

为了简洁起见,我们将设置一个基本任务,该任务执行以下操作:

  • Spit out a bundle;

    吐出一捆;
  • Transform Coffeescript via Coffeeify;

    通过Coffeeify转换Coffeescript;
  • Transform ES2015 via Babelify;

    通过Babelify转换ES2015;
  • Produce separate source maps.

    生成单独的源地图。

But if you like bells and whistles, check out the repo. It features a fancy watch task for you to get started with.

但是,如果您喜欢花俏的话,请查看回购协议。 它具有精美的监视任务,供您入门。

As always, the first step is installation:

与往常一样,第一步是安装:

npm install -g gulp && npm install gulp --save-dev

npm install -g gulp && npm install gulp --save-dev

We'll need to install a bit of a toolchain to make this work. Here's the command; the names of the dependencies are in the Gulpfile below.

我们需要安装一些工具链才能完成这项工作。 这是命令; 依赖项的名称在下面的Gulpfile中。

npm install --save-dev vinyl-source-stream vinyl-buffer gulp-livereload gulp-uglify gulp-util gulp babelify babel-preset-es2015 buffer merge rename source sourcemaps watchify

npm install --save-dev vinyl-source-stream vinyl-buffer gulp-livereload gulp-uglify gulp-util gulp babelify babel-preset-es2015 buffer merge rename source sourcemaps watchify

Swell. Now, create a Gulpfile that looks like this:

胀。 现在,创建一个如下所示的Gulpfile:

// gulpfile.js
// Heavily inspired by Mike Valstar's solution:
//   http://mikevalstar.com/post/fast-gulp-browserify-babelify-watchify-react-build/
"use strict";

var    babelify   = require('babelify'),
        browserify = require('browserify'),
        buffer     = require('vinyl-buffer'),
        coffeeify  = require('coffeeify'),
        gulp       = require('gulp'),
        gutil      = require('gulp-util'),
        livereload = require('gulp-livereload'),
        merge      = require('merge'),
        rename     = require('gulp-rename'),
        source     = require('vinyl-source-stream'),
        sourceMaps = require('gulp-sourcemaps'),
        watchify   = require('watchify');

var config = {
    js: {
        src: './main.js',       // Entry point
        outputDir: './build/',  // Directory to save bundle to
        mapDir: './maps/',      // Subdirectory to save maps to
        outputFile: 'bundle.js' // Name to use for bundle
    },
};

// This method makes it easy to use common bundling options in different tasks
function bundle (bundler) {

    // Add options to add to "base" bundler passed as parameter
    bundler
      .bundle()                                                        // Start bundle
      .pipe(source(config.js.src))                        // Entry point
      .pipe(buffer())                                               // Convert to gulp pipeline
      .pipe(rename(config.js.outputFile))          // Rename output from 'main.js'
                                                                              //   to 'bundle.js'
      .pipe(sourceMaps.init({ loadMaps : true }))  // Strip inline source maps
      .pipe(sourceMaps.write(config.js.mapDir))    // Save source maps to their
                                                                                      //   own directory
      .pipe(gulp.dest(config.js.outputDir))        // Save 'bundle' to build/
      .pipe(livereload());                                       // Reload browser if relevant
}


gulp.task('bundle', function () {
    var bundler = browserify(config.js.src)  // Pass browserify the entry point
                                .transform(coffeeify)      //  Chain transformations: First, coffeeify . . .
                                .transform(babelify, { presets : [ 'es2015' ] });  // Then, babelify, with ES2015 preset

    bundle(bundler);  // Chain other options -- sourcemaps, rename, etc.
})

Now if you run gulp bundle in your working directory, you'll have your bundle.js sitting in build/, and your bundle.js.map sitting in build/maps/.

现在,如果您在工作目录中运行gulp bundlebundle.js放在build/ ,并将bundle.js.map放在build/maps/

This config is mostly Gulp-specific detail, so I'll let the comments speak for themselves. The important thing to note is that, in our bundle task, we can easily chain transformations. This is a great example of how intuitive and fluent Browserify's API can be. Check the documentationhttps://github.com/substack/node-browserify for everything else you can do with it.

此配置主要是针对Gulp的详细信息,因此,我将让其说明自己。 需要注意的重要一点是,在我们的bundle任务中,我们可以轻松地链接转换。 这是一个很好的例子,说明Browserify的API多么直观和流畅。 查看文档 https://github.com/substack/node-browserify,了解您可以执行的其他所有操作。

结论 ( Conclusion )

Whew! What a whirlwind tour. So far, you've learned:

ew! 真是一场旋风之旅。 到目前为止,您已经了解到:

  • Why we need Browserify, and why it's awesome;

    为什么我们需要Browserify,以及为什么它很棒?
  • Where Browserify stands in relation to Webpack;

    Browserify与Webpack有关的位置;
  • How to use Browserify to build a simple bundle;

    如何使用Browserify构建简单的捆绑包;
  • How to use Browserify transforms to build not-so-simple bundles;

    如何使用Browserify转换来构建不太简单的包;
  • How to use NPM scripts to set up live reload and build tasks;

    如何使用NPM脚本设置实时重新加载和构建任务;
  • The basics of integrating Browserify with Gulp

    将Browserify与Gulp集成的基础

That's more than enough to be productive with Browserify. There are a few links you should bookmark:

这足以使Browserify发挥作用。 您应该将一些链接添加为书签:

And that about wraps it up. If you've got questions, comments, or confusions, drop a line in the comments--I'll get back to you.

到此为止。 如果您有任何疑问,评论或困惑,请在评论中添加一行-我会尽快与您联系。

Be sure to follow me on Twitter (@PelekeS) if you want a heads-up when I publish something new. Next time, we'll make that boring home page a lot more interesting by using this tooling alongside React.

如果您在我发布新内容时要注意,请确保在Twitter( @PelekeS )上关注我。 下次,通过与React一起使用此工具,我们将使无聊的主页更加有趣。

Until then, keep getting cozy with Browserify. Go build something incredible.

在此之前,请保持与Browserify的融合。 去建立一些不可思议的东西。

翻译自: https://scotch.io/tutorials/getting-started-with-browserify

browserify

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值