当前位置: 首页 > 编程日记 > 正文

打开浏览器的包 node_如何发布可在浏览器和Node中使用的软件包

打开浏览器的包 node

When you create a package for others to use, you have to consider where your user will use your package. Will they use it in a browser-based environment (or frontend JavaScript)? Will they use it in Node (or backend JavaScript)? Or both?

创建供其他人使用的软件包时,必须考虑用户将在何处使用您的软件包。 他们会在基于浏览器的环境(或前端JavaScript)中使用它吗? 他们会在Node(或后端JavaScript)中使用它吗? 或两者?

If you want to create a package that’s usable in both browsers and Node, this article is here to help.

如果您想创建一个在浏览器和Node中都可以使用的程序包,本文将为您提供帮助。

You’ll learn:

您将学到:

1. How to write packages for use in browsers

1.如何编写在浏览器中使用的包

2. How to write packages for use in Node

2.如何编写要在Node中使用的软件包

3. How to publish your packages for use in both browsers and Node

3.如何发布程序包以在浏览器和Node中使用

编写用于浏览器的软件包 (Writing a package for use in browsers)

If you want to include a library in frontend JavaScript, you have to link the library first with a script tag. You can use the library anytime after you link it.

如果要在前端JavaScript中包含库,则必须首先将库与script标签链接。 链接后,您可以随时使用该库。

<!-- This is html -->
<script src="link-to-jquery.js"></script>
<script>  // You can use jQuery anytime after you link to it  console.log(jQuery)</script>

This works because JavaScript in browsers shares one global scope. It doesn’t matter how many JavaScript files you link to. They behave as if they’re one big JavaScript file.

之所以可行,是因为浏览器中JavaScript共享一个全局范围。 链接到多少JavaScript文件无关紧要。 它们的行为就像是一个大JavaScript文件。

With this information, we can begin writing a library for use in the frontend world.

有了这些信息,我们就可以开始编写供前端世界使用的库了。

Let’s say you want to create a library called peachBlossom. peachBlossom has a bloom function. You write this bloom function in a separate JavaScript file, peach-blossom.js.

假设您要创建一个名为peachBlossom的库。 peachBlossom具有bloom功能。 您可以在单独JavaScript文件peach-blossom.js编写此bloom函数。

// This is js
// peach-blossom.jsfunction bloom () {  console.log('Bloom!')}

You can include peachBlossom in your frontend JavaScript by linking to the peach-blossom.js file. Once you do this, you can use bloom anywhere.

您可以通过链接到peach-blossom.js文件在前端JavaScript中包含peachBlossom 。 完成此操作后,您可以在任何地方使用bloom

<!-- This is html -->
<script src="peach-blossom.js"></script><script src="main.js"></script>
// This is js
// main.jsbloom() // Bloom!

Libraries usually have more than one piece of code. We don’t want to pollute the global scope with little variables. What we can do is wrap the functions we want to expose in an immediately-invoked function expression (IIFE).

图书馆通常有多个代码。 我们不想用很少的变量来污染全局范围。 我们可以做的是将要公开的函数包装在立即调用的函数表达式(IIFE)中。

This means:

这表示:

1. We create a function and run it immediately2. We return the library from within the function so we can use the library later.

1.我们创建一个函数并立即运行它。 我们从函数中返回库,以便以后使用。

In code, it looks somewhat like this:

在代码中,它看起来像这样:

// This is js
// peach-blossom.js const peachBlossom = (function () {  // Write as much code as you want here
// Return what others can use  return {    bloom: function () {      console.log('Bloom!')    }  }})()

You can then use bloom anywhere by writing peachBlossom.bloom.

然后,可以通过编写peachBlossom.bloom在任何地方使用bloom

// This is js
// main.jspeachBlossom.bloom() // Bloom!

This is the basics of writing a frontend library.

这是编写前端库的基础。

Now, let’s talk about writing a library for Node.

现在,让我们谈谈为Node编写一个库。

为Node编写一个包 (Writing a package for Node)

Adding a library to Node is different from adding a library to browsers. This is because Node doesn’t have HTML files and <script> tags.

向Node添加库与向浏览器添加库不同。 这是因为Node没有HTML文件和<scri pt>标签。

Let’s make sure you know how to run Node before we begin writing a library for Node.

在开始为Node创建库之前,请确保您知道如何运行Node。

运行节点 (Running Node)

First, you need to make sure you have Node installed on your computer. You can install Node from Node’s website if you don’t have it installed already.

首先,您需要确保在计算机上安装了Node。 如果尚未安装Node,则可以从Node的网站安装。

Once you have Node installed, you’ll want to create a folder to store your Node project. In this case, let’s call it “node-project”.

安装Node之后,您将要创建一个文件夹来存储Node项目。 在这种情况下,我们称其为“ node-project”。

The command to create a folder is this:

创建文件夹的命令是这样的:

# This is bash
mkdir node-project

Then, you need to navigate to the node-project directory. You can do it with cd:

然后,您需要导航到node-project目录。 您可以使用cd来做到这一点:

# This is bashcd node-project

If you’re having problems with the command line, you can use this guide to help you out.

如果您在命令行方面遇到问题,则可以使用本指南为您提供帮助。

Next, we want to create a file. This will be a JavaScript file. (We will run Node on this file). Let’s call it index.js.

接下来,我们要创建一个文件。 这将是一个JavaScript文件。 (我们将在此文件上运行Node)。 我们称之为index.js

# This is bash
touch index.js

In index.js, we’re going to write a console.log statement. This is for us to know if we run the file.

index.js ,我们将编写一个console.log语句。 这是为了让我们知道是否运行文件。

// This is js
// index.jsconsole.log('Running index.js!')

Finally, you can use node to run index.js. Here’s the command:

最后,您可以使用node运行index.js 。 这是命令:

# This is bash
node index.js

Once you run index.js, you should see the console.log in the terminal. That’s how we know the file has run.

一旦运行index.js ,您应该在终端中看到console.log 。 这就是我们知道文件已运行的方式。

将库添加到Node (Adding libraries to Node)

To add libraries to Node, you have to use the require statement. Once you add a library, you can use the library anywhere in the same JavaScript file.

要将库添加到Node,必须使用require语句。 添加库后,您可以在同一JavaScript文件中的任何位置使用该库。

Here’s an example:

这是一个例子:

// This is js
const fs = require('fs')console.log(fs)

When you use require, Node looks for the library you specified in three places:

当使用require ,Node在三个位置查找您指定的库:

First, it checks whether the library is built into Node. In this example, fs is built directly into Node. You can use fs anytime if you use Node.

首先,它检查该库是否内置在Node中。 在此示例中, fs直接内置在Node中。 如果使用Node,则可以随时使用fs

Second, it checks whether the library exists in the node_modules folder. These are user-installed libraries. You can add a library to the node_modules folder by running npm install.

其次,它检查该库是否存在于node_modules文件夹中。 这些是用户安装的库。 您可以通过运行npm install将库添加到node_modules文件夹中。

Here’s an example where we install express, then require express in Node:

这是我们安装express ,然后在Node中要求express的示例:

# This is bash
# Run this in the command linenpm install express
// This is js
// Index.js const express = require('express')console.log(express)

Third, if you add ./ to require, Node will look for a file located in the current directory. This is where we can begin writing the peach-blossom library.

第三,如果您添加./require ,Node将在当前目录中查找文件。 这是我们开始编写peach-blossom库的地方。

为Node编写第一个库 (Writing your first library for Node)

Let’s start by creating a peach-blossom.js file. This file should be in the same directory as index.js.

首先创建一个peach-blossom.js文件。 该文件应与index.js在同一目录中。

// This is js
touch peach-blossom.js

We can add peach-blossom.js to index.js by using require. Here’s what it looks like:

我们可以通过使用requirepeach-blossom.js添加到index.js 。 看起来是这样的:

// This is js
const peachBlossom = require('./peach-blossom')

In Node, there’s no concept of a shared global scope. Each file has its own scope. So, if you write peach-blossom.js as if it’s used for frontend JavaScript, you won’t be able to use it. You’ll get an error.

在Node中,没有共享全局范围的概念。 每个文件都有其自己的范围。 因此,如果您将peach-blossom.js为好像用于前端JavaScript,则将无法使用它。 您会得到一个错误。

// This is js
// peach-blossom.js const peachBlossom = (function () { // Write as much code as you want here
// Return what others can use return { bloom: function () { console.log(‘Bloom!’) } }})()
// This is js
// index.js const peachBlossom = require(‘./peach-blossom’)

To pass variables from one file to another in Node, you have to write module.exports. Variables passed to module.exports can be retrieved from another file.

要将变量从Node中的一个文件传递到另一个文件,必须编写module.exports 。 传递给module.exports变量可以从另一个文件中检索。

This means we must write module.exports in peach-blossom.js.

这意味着我们必须写module.exportspeach-blossom.js

// This is js
// Write as much code as you want here const peachBlossom = { bloom () { console.log(‘Bloom!’) }}
// Exports peachBlossom for use in other filesmodule.exports = peachBlossom

Once we have exported peachBlossom, we can use it in other files:

导出peachBlossom ,可以在其他文件中使用它:

// This is js
// index.js const peachBlossom = require('./peach-blossom')peachBlossom.bloom() // Bloom!```

This format of passing variables around in Node with require and module.exports is called CommonJS.

在Node中使用requiremodule.exports传递变量的这种格式称为CommonJS

将库发布为npm软件包 (Publishing your library as an npm package)

In short, to make your module work in Node, you have to export a variable with module.exports. Other people can then require this module in their code.

简而言之,要使模块在Node中工作,必须使用module.exports导出变量。 然后其他人可以在其代码中require此模块。

At this point, you can move peach-blossom into a separate project folder and publish it as an npm package. You can use this guide to find out more about publishing the process.

此时,您可以将peach-blossom移到一个单独的项目文件夹中,并将其作为npm软件包发布。 您可以使用本指南查找有关发布流程的更多信息。

编写可在前端和后端JavaScript中使用的模块 (Writing modules that are usable in both frontend and backend JavaScript)

Let’s take a moment to reconcile what we know.

让我们花一点时间来调和我们所知道的。

To write a library for the frontend, we need to declare it as a variable. As much as possible, we want to expose one variable only.

要为前端编写库,我们需要将其声明为变量。 我们尽可能只公开一个变量。

// This is js
const peachBlossom = (function () {  // Write as much code as you want here
// Return what others can use  return {    bloom: function () {      console.log('Bloom!')    }  }})()

To write a library for the Node, we need to export the variable with module.exports. Here, we only expose one variable.

要为Node编写一个库,我们需要使用module.exports导出变量。 在这里,我们只公开一个变量。

// This is js// Write as much code as you want here const peachBlossom = {  bloom () {    console.log('Bloom!')  }}
// Exports peachBlossom for use in other filesmodule.exports = peachBlossom

But these are two completely different formats! How can we write a library once and use it in both contexts?

但是,这是两种完全不同的格式! 我们如何编写一次库并在两种情况下使用它?

Enter UMD.

输入UMD。

UMD (UMD)

UMD (Universal Module Definition) is a block of code we can use to wrap around our library. This block of code makes it possible to use a library both on the frontend and in Node.

UMD(通用模块定义 )是我们可以用来包装我们库的代码块。 此代码块可以在前端和Node中使用库。

It kinda looks like this:

看起来像这样:

// This is js
(function (root, factory) {    if (typeof define === 'function' && define.amd) {        // AMD. Register as an anonymous module.        define(['b'], factory);    } else if (typeof module === 'object' && module.exports) {        // Node.        module.exports = factory(require('b'));    } else {        // Browser globals (root is window)        root.returnExports = factory(root.b);    }}(typeof self !== 'undefined' ? self : this, function (b) {    // Use b in some fashion.
// Just return a value to define the module export.    // This example returns an object, but the module    // can return a function as the exported value.    return {};}));

Whoa! This is confusing! Hold up!

哇! 这很混乱! 耽误!

In practice, we don’t have to know how to UMD-ify our code by ourselves. Many tools, like Webpack and Parcel, gives us the ability to UMD-ify our code through them.

在实践中,我们不必知道如何自己对UMD修改代码。 Webpack和Parcel等许多工具使我们能够通过它们进行UMD修改代码。

Here are some examples (and their relevant setup instructions):

以下是一些示例(及其相关的设置说明):

1. Gulp-umd2. Webpack3. Parcel4. Rollup

1. Gulp-umd 2. Webpack 3. Parcel 4. 汇总

This, means you have to set up these tools if you want to write packages that can be used for both Frontend JavaScript and in Node. Yes, it complicates the authoring process, but there’s nothing much we can do about it at this point.

这意味着,如果要编写可用于前端JavaScript和Node中的程序包,则必须设置这些工具。 是的,这使创作过程复杂化,但是目前我们无能为力。

结语 (Wrapping up)

If you want your library to work both on Frontend JavaScript and in Node, you need to wrap your module with UMD (Universal Module Definition).

如果希望您的库在前端JavaScript和Node上都能工作,则需要使用UMD(通用模块定义)包装模块。

If you want to UMD-ify your code, you need to use a build tool when you author your package. This makes the authoring process more complicated. But the tradeoff can be worth it for providing users with an option to use your library anywhere.

如果要UMD修改代码,则在编写程序包时需要使用构建工具。 这使创作过程更加复杂。 但是,权衡取舍是值得的,因为它为用户提供了在任何地方使用您的库的选项。

This article was originally posted on my blog.Sign up for my newsletter if you want more articles to help you become a better frontend developer.

本文最初发布在我的博客上。如果您想要更多文章来帮助您成为更好的前端开发人员,请注册我的新闻通讯 。

翻译自: https://www.freecodecamp.org/news/how-to-publish-packages-that-can-be-used-in-browsers-and-node-c51274dca77c/

打开浏览器的包 node

相关文章:

存储过程中SELECT与SET对变量赋值

Create proc insert_bookparam1char(10),param2varchar(20),param3money,param4moneyoutputwith encryption---------加密asinsert into book(编号,书名,价格)Values(param1,param2,param3)select param4sum(价格) from bookgo执行例子&#xff1a;declare total_price moneyex…

AngularJs $resource 高大上的数据交互

$resource 创建一个resource对象的工厂函数&#xff0c;可以让你安全的和RESFUL服务端进行数据交互。 需要注入 ngResource 模块。angular-resource[.min].js 默认情况下&#xff0c;末尾斜杠&#xff08;可以引起后端服务器不期望出现的行为&#xff09;将从计算后的URL中剥离…

样式集(四)搜索框样式

上图&#xff1a; 代码&#xff1a; // pages/search/search.js var textPage({data: {input_val:"",list:[]},input_p(e){this.setData({input_val:e.detail.value})},onLoad: function (options) {}, }) <view classpage_row bindtap"suo"><vi…

初步了解React Native的新组件库firstBorn

first-born is a React Native UI Component Framework, which follows the design methodology Atomic Design by Brad Frost.first-born是React Native UI组件框架&#xff0c;它遵循Brad Frost的设计方法Atomic Design 。 Version 1.0.0 was recently published as an npm …

less里面calc() 语法

转载 Less的好处不用说大家都知道&#xff0c;确实让写CSS的人不在痛苦了&#xff0c;最近我在Less里加入calc时确发现了有点问题&#xff0c;我在Less中这么写&#xff1a;  div {  width : calc(100% - 30px);  }  结果Less把这个当成运算式去执行了&#xff0c;结果…

基于XMPP的IOS聊天客户端程序(XMPP服务器架构)

最近看了关于XMPP的框架&#xff0c;以文本聊天为例&#xff0c;需要发送的消息为&#xff1a; <message type"chat" from"kangserver.com" to"testserver.com"> <body>helloWord</body> </message> …

小程序云开发,判断数据库表的两个字段匹配 云开发数据库匹配之 and 和 or 的配合使用

云开发数据库匹配之 and 和 or 的配合使用 代码&#xff1a; // 获取成员消息onMsg2() {let that thiswx.cloud.init({env: gezi-ofhmx})const DB wx.cloud.database()const _ DB.command;var aa "1"var bb "2"DB.collection(message_logging).where…

react引入多个图片_重新引入React:v16之后的每个React更新都已揭开神秘面纱。

react引入多个图片In this article (and accompanying book), unlike any you may have come across before, I will deliver funny, unfeigned and dead serious comic strips about every React update since v16. It’ll be hilarious, either intentionally or unintention…

75. Find Peak Element 【medium】

75. Find Peak Element 【medium】 There is an integer array which has the following features: The numbers in adjacent positions are different.A[0] < A[1] && A[A.length - 2] > A[A.length - 1].We define a position P is a peek if: A[P] > A[P-1…

云开发地图标记导航 云开发一次性取所有数据

地图取 elx 表格的经纬度数据&#xff0c;存到云开发数据库里面&#xff0c;然后标记在地图上&#xff0c;点击地图的标记可以实现路线规划&#xff0c;导航&#xff0c;拨打电话。 elx数据格式如下&#xff1a; 云开发的数据库不能直接导入elx&#xff0c;所以需要转换为csv文…

未能加载文件或程序集“Report.Basic”或它的某一个依赖项。试图加载格式不正确的程序...

出现问题如下&#xff1a; 解决办法&#xff1a; 这是由于没有开启32位程序兼容模式 具体操作如下&#xff1a;找到对应的程序池--------高级设置-------修改“启用32位应用程序”状态修改为true 转载于:https://www.cnblogs.com/OliverQin/p/5018575.html

flutter开发小程序_为什么我认为Flutter是移动应用程序开发的未来

flutter开发小程序I dabbled a bit in Android and iOS development quite a few years back using Java and Objective-C. After spending about a month working with both of them, I decided to move on. I just couldn’t get into it.几年前&#xff0c;我使用Java和Obje…

小程序获取图片的宽高

代码&#xff1a; imgInfo(url){wx.getImageInfo({src: url,success (res) {console.log(res.width)console.log(res.height)return {width:res.width,height:res.height}}})},

凯撒密码、GDP格式化输出、99乘法表

1.恺撒密码的编码 plaincode input(明文&#xff1a;)print(密文&#xff1a;,end)for i in plaincode: print(chr(ord(i)3),end) 2.国家名称 GDP总量&#xff08;人民币亿元&#xff09; 中国 &#xffe5;765873.4375澳大利亚 &#xffe5; 78312.4375&#xff08;国家名称左…

random类的使用

小栗子a如下: string[] punch new[] { "石头", "剪刀", "布" }; string myPunch; public string MyPunch{get{Random random new Random();int Index random.Next(3);myPunch punch[Index].ToString();return myPunch;}} 转载于:https://ww…

如何使用C#在ASP.NET Core中轻松实现QRCoder

by Yogi由瑜伽士 如何使用C&#xff03;在ASP.NET Core中轻松实现QRCoder (How to easily implement QRCoder in ASP.NET Core using C#) QRCoder is a very popular QR Code implementation library written in C#. It is available in GitHub. Here I am going to implement…

简述软件配置管理

http://blog.csdn.net/zhangmike/article/details/470477本文用菊子曰发布转载于:https://www.cnblogs.com/sdsunjing/p/5019791.html

startActivityForResult和setResult详解

startActivityForResult和setResult详解 原文:startActivityForResult和setResult详解startActivityForResult与startActivity的不同之处在于&#xff1a;1、startActivity( ) 仅仅是跳转到目标页面&#xff0c;若是想跳回当前页面&#xff0c;则必须再使用一次startActivity( …

小程序瀑布流实现

实现思路&#xff1a;把图片分成两排&#xff0c;创建两个数组&#xff0c;计算总数组中图片的宽高&#xff0c;对比上一个图片和当前的图片高度&#xff0c;低的就给另一个数组添加。效果图&#xff1a; 上代码&#xff1a; // miniprogram/pages/find/index.js const app g…

Webhooks上的一个简单方法:恐吓现在停止

Webhook.Webhook。 It sounds like what happens when you cross a spider and a pirate. In the world of the internet though, webhooks are something completely different. Webhooks help connect services together.听起来就像当您越过蜘蛛和海盗时会发生什么。 但是&a…

12.MySql关于获取当前时间的三个函数

这三个函数都是获取当前时间的&#xff0c;获取的详细格式如下图所示&#xff0c;可以根据需要来选用。 转载于:https://www.cnblogs.com/Nick-Hu/p/7566805.html

微信小程序云开发,使用阿里云短信服务,搜索员工生日定期发送短信。

相关API文档地址&#xff1a; 阿里云短信服务API文档地址 小程序云开发云函数正则匹配API文档地址 小程序云开发云函数定时触发器 1.登录阿里云&#xff0c;购买短信服务并添加签名和模板 2.&#xff0c; 登录阿里云&#xff0c;鼠标放在右上角的头像图标就会显示 AccessKey…

信息安全系统设计基础家庭作业

《深入理解计算机系统》家庭作业 * 8.9 答案&#xff1a; 进程对 是否并发 AB 否 AC 是 AD 是 BC 是 BD 是 CD 是 * 8.10 答案&#xff1a; A. 调用一次&#xff0c;返回两次&#xff1a; fork B. 调用一次&#xff0c;从不返回&#xff1a; execve, longjmp C. 调…

css游戏代码_介绍CSSBattle-第一个CSS代码搜寻游戏

css游戏代码by kushagra gour由kushagra gour 介绍CSSBattle-第一个CSS代码搜寻游戏 (Introducing CSSBattle — the first CSS code-golfing game) If you are learning Web development or are already a professional Web developer, there is a very high chance you have…

IOS手机全屏长按识别二维码HTML代码

代码段作用讲解&#xff1a; 1. 二维码的全屏样式, opacity: 0; 透明样式&#xff0c; touch-callout: none; -webkit-touch-callout: none; -ms-touch-callout: none; -moz-touch-callout: none; 禁止IOS默认长按事件 .codePage {position: absolute;touch-callout: none;…

[亲测]在Mac下配置php开发环境:Apache+php+MySql

公司给我们配上了高大上的Apple Mac Pro本本&#xff0c;这两天自己正在习惯中。通过虚拟机PD&#xff0c;确实解决了一些因为工作习惯无法在iOS上很好完成的事情&#xff0c;但是我想&#xff0c;既然用起了iOS就尽量将一些事务在iOS环境下处理&#xff0c;免得好似关羽耍着大…

RabbitMQ 异常与任务分发

RabbitMQ 异常与任务分发 异常情况处理 上篇最后提到了这个问题&#xff0c; consumer异常退出、queue出错、甚至rabbitMQ崩溃。因为它们都是软件 &#xff0c;软件都会有bug&#xff0c;这是无法避免的。所以RabbitMQ在设计的时候也想到了这一点 在之前&#xff0c;消息分发给…

reddit_如何使用Python创建自定义Reddit通知系统

redditby Kelsey Wang王凯西 如何使用Python创建自定义Reddit通知系统 (How to make a custom Reddit notification system with Python) Don’t you just love automated emails? I know I do. I mean, who doesn’t enjoy waking up to 236 new messages from Nike, Ticket…

1016. Phone Bills (25)

时间限制400 ms内存限制65536 kB代码长度限制16000 B判题程序Standard作者CHEN, Yue去掉非法数据计算账单A long-distance telephone company charges its customers by the following rules:Making a long-distance call costs a certain amount per minute, depending on the…

样式集(五)微信朋友圈样式模拟

效果图&#xff1a; 小图标&#xff1a; 源码&#xff1a; <!--pages/findList/findList.wxml--> <image class"xxiangji" catchtap"xxiangji" src"/images/xxiangji.png"></image> <image class"top_img" src&…