Simple Ethers.js Usage Example for Beginners

In this Ethers.js article we will Learn about Simple Ethers.js Usage Example for Beginners. Although outlined code snippets are great when developing, having access to a proper ethers.js tutorial that instructs novice developers and serves as a reminder for experienced ones can take any development project to the next level. Moving forward, we will not only outline code snippets but also provide step-by-step instructions on how to get started with ethers.js, and we’ll do so with the help of a simple ethers.js example. That said, aside from exploring ethers.js examples, you can also use Web3.js as an alternative. However, in the last two years (or so), most dapp (decentralized application) developers have been more inclined toward ethers.js. Why? For example, it’s easier to listen to the blockchain with ethers.js, which we’ll look closer at in this tutorial! 

We will first ensure you can answer the “what is ethers.js?” question. This is where you’ll also learn about the core features of this practical JS tool. Then, we’ll examine the main benefits of using ethers.js. With the basics under our belt, we’ll take you through our ethers.js tutorial. By following our lead, you’ll be able to create your ethers.js example script and learn how to use ethers.js. 

However, you should keep in mind that there’s an even smoother solution for listening to on-chain events – Moralis’ Streams API. Thus, we’ll redo the same ethers.js example but use the Streams API instead. We’ll also point out some key advantages of this next-level solution. Nonetheless, you’ll even learn how to use a neat UI to go beyond ethers.js examples. As such, create your free Moralis account, which is all you need to start using Moralis Streams.   

scale ethers.js in this tutorial - sign up to get started

Exploring Ethers.js – What is it?

Just like Web3.js, ethers.js is a Web3 JavaScript library. Since its release in 2016, this tool for blockchain interaction has experienced impressive adoption. Everyone who has ever used this JS library can thank Richard Moore, the man behind ethers.js. It is safe to say that ethers.js is the most popular open-source Ethereum JS library. It features millions of downloads and has surpassed Web3.js in daily downloads by more than 60% in 2022 

For more information, read our Web3.js vs ethers.js comparison. 

purple background with white text stating ethers.js

If you know a thing or two about any conventional programming library, you won’t be surprised to hear that ethers.js consists of a collection of prewritten code snippets. The latter can be used to perform many recurring functions and, thus, avoid reinventing the wheel. Of course, ethers.js’ functionalities focus on Web3 via Ethereum (ETH) and other EVM-compatible blockchains. As such, this ETH JS library enables you to communicate easily and interact with decentralized networks. Over time, ethers.js has expanded and become quite a general-purpose library for Web3 development. Furthermore, it’s been successful at fulfilling its goals of being a complete and compact solution for developers looking to interact with the Ethereum chain. 

Because this JS library offers many features, this results in countless ethers.j examples. However, when listening to blockchain events, ethers.js’ option to connect to Ethereum nodes using JSON-RPC, Etherscan, MetaMask, Infura, Alchemy, or Cloudflare is the key. However, this also means you have to worry about one of these node providers. We’ll explain how to avoid that later on, but for now, let’s focus on ethers.js features. 

features are written in chalk on a chalkboard

Main Features of Ethers.js 

Aside from enabling you to connect to Ethereum node providers, ethers.js maintains many other features, which enables you to cover the following aspects:

  • Create JavaScript objects from any contract ABI, including ABIv2 and ethers’ Human-Readable ABI, with meta classes.
  • Keep your private keys in your client safe.
  • Import and export JSON wallets (Geth and Parity).
  • Use ENS names as first-class citizens anywhere an Ethereum address can be used.
  • Import and export BIP 39 mnemonic phrases (twelve-word backup phrases) and HD wallets in several languages. 

megaphone shouting benefits

Benefits of Using Ethers.js

Ethers.js features a small bundle size, extensive and straightforward documentation, and a user-friendly API structure. Furthermore, it is intuitive and straightforward to use. Also, aside from JavaScript, ethers.js supports TypeScript (TS). All these benefits, combined with the above-listed features, make ethers.js a highly attractive library for many Web3 developers. 

Let’s look at a sum of ethers.js’ main benefits:

  • Minimal size – ethers.js is tiny, only 88 KB compressed and 284 KB uncompressed.
  • Includes extensive documentation.
  • Comes with a large collection of maintained test cases.
  • Ethers.js includes definition files and complete TS sources – it is fully TypeScript-ready.
  • Comes with an open-source MIT license that includes all dependencies.

Aside from these ethers.js-specific benefits, learning how to use ethers.js brings some universal advantages. After all, blockchain is here to stay and poised to radically change how the world operates. Thus, you may use this ethers.js tutorial, knowing that it’s helping you learn to become part of that solution. 

Moreover, some of the most common ethers.js examples revolve around creating whale alerts, building automated bots, monitoring NFT collections, Web3 game notifications, etc. Ultimately, when listening to on-chain events either with ethers.js or other reliable tools, your main objective is to execute actions automatically as a response to specific on-chain events occurring. So, your goal must be to choose a tool that will enable you to do that effectively and efficiently.

code editor with an ethers.js file

Tutorial on How to Use Ethers.js – Get Started with an Ethers.js Example

It’s time we show you how to use ether.js by tackling our ethers.js tutorial. To make things as convenient for you as possible, you can use our ethers.js example script (“index.js”) found below. However, let’s still guide you through the code. So, in the top line, you must first ensure that your NodeJS file uses ethers.js. Then, you must import the application binary interface (ABI), which is specific to every smart contract. That said, the “getTransfer” async function deserves your main attention. After all, the latter takes care of listening to the blockchain. 

Using our ethers.js example script, you’ll focus on the USDC contract address. Of course, you could convert it to other ethers.js examples by using other contract addresses. Furthermore, the “getTransfer” function below relies on the ethers.js library’s “WebSocketProvider” endpoint. By using this endpoint, you can define the node provider you want to use. To make that work, you must also obtain that provider’s key, which is an important aspect of how to use ethers.js. The example code below focuses on Alchemy. However, you should use a node provider that supports the chain(s) you want to focus on.

Aside from a contract address and provider, the “getTransfer” function also accepts an ABI. Last but not least, you also need to set up a “transfer” listener. The latter will also console-log the relevant on-chain details.

multiple lines of code

Exploring Our Ethers.js Tutorial Script

Below is our example script that is the core of today’s ethers.js tutorial. So, make sure to copy the entire script and test it:

const ethers = require("ethers");
const ABI = require("./abi.json");
require("dotenv").config();

async function getTransfer(){
    const usdcAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; ///USDC Contract
    const provider = new ethers.providers.WebSocketProvider(
        `wss://eth-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_KEY}`
    );

    const contract = new ethers.Contract(usdcAddress, ABI, provider);

    contract.on("Transfer", (from, to, value, event)=>{

        let transferEvent ={
            from: from,
            to: to,
            value: value,
            eventData: event,
        }

        console.log(JSON.stringify(transferEvent, null, 4))

    })
}

getTransfer()

Once you have the above lines of code in place, you can run the script using the following command:

node index.js

In response, you should see the results in your terminal:

code structure result from using the script inside this ethers.js tutorial

There are countless ethers.js examples that we could focus on; however, the above ethers.js tutorial provides you with more than enough to get going. Moreover, looking at the results of the above script, you can see that ethers.js provides you with quite a lot of details. Unfortunately, however, these details come in the form of un-parsed data. This is one of the main reasons why instead of learning how to use ethers.js, many devs focus on utilizing Moralis’ Streams API. 

moralis streams api is written in black on a white background

Use a Better Ethers.js Example

Above, you were able to see ethers.js in action, and if you took our example script for a spin, you even saw firsthand that ethers.js obtains real-time events. Consequently, it would be wrong to call this ETH JS library anything less than a very decent open-source solution for listening to the blockchain. Yet, ethers.js comes with some limitations. Trying to overcome these limitations as you go about developing your dapps can be quite costly. Hence, the above ethers.js tutorial wouldn’t be complete without pointing out the main ethers.js’ limitations:

  • Cannot provide you with 100% reliability
  • You can’t filter on-chain events from the gate 
  • Inability to take into account multiple addresses
  • You can’t listen to wallet addresses 

On the other hand, the Moralis Streams API covers all those aspects. This makes it the ultimate solution for streaming blockchain data. That said, you can find a more detailed ethers.js vs Web3 streams comparison on our blog; however, the following image shows the gist of it: 

table showing a side-by-side comparison of an ethers.js example and moralis streams api

With that said, let’s tackle the above ethers.js tutorial with Moralis Streams.

Streams API – More Powerful Than Any Ethers.js Examples

The goal of this subsection is to obtain the same on-chain data as above – any USDC transfer on Ethereum. However, instead of using ether.js, Moralis’ Streams API will be our tool. If you want to follow our lead, create another “index.js” file and make sure to import Moralis and its utils at the top:

const Moralis = require("moralis").default;
const Chains = require("@moralisweb3/common-evm-utils");
const EvmChain = Chains.EvmChain;
const ABI = require("./abi.json");
require("dotenv").config();

const options = {
  chains: [EvmChain.ETHEREUM],
  description: "USDC Transfers 100k",
  tag: "usdcTransfers100k",
  includeContractLogs: true,
  abi: ABI,
  topic0: ["Transfer(address,address,uint256)"],
  webhookUrl: "https://22be-2001-2003-f58b-b400-f167-f427-d7a8-f84e.ngrok.io/webhook",
  advancedOptions: [
    {
        topic0: "Transfer(address,address,uint256)",
        filter: {
            gt : ["value", "100000"+"".padEnd(6,"0")]
        }
    }
]

};

Moralis.start({
  apiKey: process.env.MORALIS_KEY ,
}).then(async () => {
  const stream = await Moralis.Streams.add(options);
  const { id } = stream.toJSON();

  await Moralis.Streams.addAddress({
      id: id,
      address: ["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"]
  })
});

Looking at the lines of code above, you can see that the script focuses on the same ABI and the same contract address. The script also covers the options that the Streams API provides. This is also where we used “ETHEREUM” to focus on that chain. However, since Moralis is all about cross-chain interoperability, we could easily target any other chain or multiple chains simultaneously.

Furthermore, the above script also initiates Moralis using your Moralis Web3 API key. Fortunately, anyone with a free Moralis account gets to obtain that key in two steps:

web3 api landing page showing the api key

Among the bottom lines of the above code, you can see the “addAddress” endpoint. The latter enables you to add multiple addresses and listen to them simultaneously. To see that option in action, make sure to use the video below. This is also the place to learn how to create and manage streams using a neat UI.

Ultimately, when using Moralis’ Streams API, we receive parsed data. Also, not only do we receive transactions hashes and from and to addresses, but we also receive transfer values:

The video tutorial below also demonstrated how to use the filtering feature of this powerful “ethers.js 2.0” tool.

Ethers.js Tutorial – How to Get Started Using a Simple Ethers.js Example – Summary

In today’s article, you had an opportunity to learn all you need to know about ethers.js – the leading ETH JavaScript library. As such, you now know the core features and main benefits of using this library. You also had a chance to follow our ethers.js tutorial to take this JS library for a spin. Also, you learned that despite ethers.js’s great power, it has several limitations. However, you also learned that you could bridge these limitations using Moralis’ Streams API. In fact, you were able to follow our lead and redo the ethers.js tutorial but using Moralis Streams instead. Last but not least, following a detailed video tutorial, you had an opportunity to see how filtering works, how you can listen to multiple addresses, and how to use the Moralis Streams UI.

streams landing page from moralis

Following the trends and devs’ preferences, it’s safe to say that the Streams API is the tool of the future. Thus, make sure to learn how to work with it properly by visiting the Streams API documentation page. This is also the place to find quick-start tutorials and many examples. By exploring other pages of the Moralis docs, you can master all of Moralis’ tools. By doing so, you’ll be a confident dapp developer with your legacy skills. 

Furthermore, remember to explore other blockchain development topics covered on the Moralis YouTube channel and the Moralis blog. Some of the latest articles explain how to get all tokens owned by a wallet, what ERC 1155 NFTs are, and what the Sepolia testnet is. In addition, if you’d like to understand Web3 storage, make sure to read our articles explaining how Web3 data storage works, what web3.storage is, how to use metadata for NFT storage, using IPFS for NFT metadata, and why developers should opt for the market’s leading Web3 provider when wanting to upload files to IPFS. You can also take a more professional approach to your crypto education – enroll in Moralis Academy and master blockchain and Bitcoin fundamentals

Original article sourced at: https://moralis.io

#Ethers.js 

What is GEEK

Buddha Community

Simple Ethers.js Usage Example for Beginners
Lawrence  Lesch

Lawrence Lesch

1677668905

TS-mockito: Mocking Library for TypeScript

TS-mockito

Mocking library for TypeScript inspired by http://mockito.org/

1.x to 2.x migration guide

1.x to 2.x migration guide

Main features

  • Strongly typed
  • IDE autocomplete
  • Mock creation (mock) (also abstract classes) #example
  • Spying on real objects (spy) #example
  • Changing mock behavior (when) via:
  • Checking if methods were called with given arguments (verify)
    • anything, notNull, anyString, anyOfClass etc. - for more flexible comparision
    • once, twice, times, atLeast etc. - allows call count verification #example
    • calledBefore, calledAfter - allows call order verification #example
  • Resetting mock (reset, resetCalls) #example, #example
  • Capturing arguments passed to method (capture) #example
  • Recording multiple behaviors #example
  • Readable error messages (ex. 'Expected "convertNumberToString(strictEqual(3))" to be called 2 time(s). But has been called 1 time(s).')

Installation

npm install ts-mockito --save-dev

Usage

Basics

// Creating mock
let mockedFoo:Foo = mock(Foo);

// Getting instance from mock
let foo:Foo = instance(mockedFoo);

// Using instance in source code
foo.getBar(3);
foo.getBar(5);

// Explicit, readable verification
verify(mockedFoo.getBar(3)).called();
verify(mockedFoo.getBar(anything())).called();

Stubbing method calls

// Creating mock
let mockedFoo:Foo = mock(Foo);

// stub method before execution
when(mockedFoo.getBar(3)).thenReturn('three');

// Getting instance
let foo:Foo = instance(mockedFoo);

// prints three
console.log(foo.getBar(3));

// prints null, because "getBar(999)" was not stubbed
console.log(foo.getBar(999));

Stubbing getter value

// Creating mock
let mockedFoo:Foo = mock(Foo);

// stub getter before execution
when(mockedFoo.sampleGetter).thenReturn('three');

// Getting instance
let foo:Foo = instance(mockedFoo);

// prints three
console.log(foo.sampleGetter);

Stubbing property values that have no getters

Syntax is the same as with getter values.

Please note, that stubbing properties that don't have getters only works if Proxy object is available (ES6).

Call count verification

// Creating mock
let mockedFoo:Foo = mock(Foo);

// Getting instance
let foo:Foo = instance(mockedFoo);

// Some calls
foo.getBar(1);
foo.getBar(2);
foo.getBar(2);
foo.getBar(3);

// Call count verification
verify(mockedFoo.getBar(1)).once();               // was called with arg === 1 only once
verify(mockedFoo.getBar(2)).twice();              // was called with arg === 2 exactly two times
verify(mockedFoo.getBar(between(2, 3))).thrice(); // was called with arg between 2-3 exactly three times
verify(mockedFoo.getBar(anyNumber()).times(4);    // was called with any number arg exactly four times
verify(mockedFoo.getBar(2)).atLeast(2);           // was called with arg === 2 min two times
verify(mockedFoo.getBar(anything())).atMost(4);   // was called with any argument max four times
verify(mockedFoo.getBar(4)).never();              // was never called with arg === 4

Call order verification

// Creating mock
let mockedFoo:Foo = mock(Foo);
let mockedBar:Bar = mock(Bar);

// Getting instance
let foo:Foo = instance(mockedFoo);
let bar:Bar = instance(mockedBar);

// Some calls
foo.getBar(1);
bar.getFoo(2);

// Call order verification
verify(mockedFoo.getBar(1)).calledBefore(mockedBar.getFoo(2));    // foo.getBar(1) has been called before bar.getFoo(2)
verify(mockedBar.getFoo(2)).calledAfter(mockedFoo.getBar(1));    // bar.getFoo(2) has been called before foo.getBar(1)
verify(mockedFoo.getBar(1)).calledBefore(mockedBar.getFoo(999999));    // throws error (mockedBar.getFoo(999999) has never been called)

Throwing errors

let mockedFoo:Foo = mock(Foo);

when(mockedFoo.getBar(10)).thenThrow(new Error('fatal error'));

let foo:Foo = instance(mockedFoo);
try {
    foo.getBar(10);
} catch (error:Error) {
    console.log(error.message); // 'fatal error'
}

Custom function

You can also stub method with your own implementation

let mockedFoo:Foo = mock(Foo);
let foo:Foo = instance(mockedFoo);

when(mockedFoo.sumTwoNumbers(anyNumber(), anyNumber())).thenCall((arg1:number, arg2:number) => {
    return arg1 * arg2; 
});

// prints '50' because we've changed sum method implementation to multiply!
console.log(foo.sumTwoNumbers(5, 10));

Resolving / rejecting promises

You can also stub method to resolve / reject promise

let mockedFoo:Foo = mock(Foo);

when(mockedFoo.fetchData("a")).thenResolve({id: "a", value: "Hello world"});
when(mockedFoo.fetchData("b")).thenReject(new Error("b does not exist"));

Resetting mock calls

You can reset just mock call counter

// Creating mock
let mockedFoo:Foo = mock(Foo);

// Getting instance
let foo:Foo = instance(mockedFoo);

// Some calls
foo.getBar(1);
foo.getBar(1);
verify(mockedFoo.getBar(1)).twice();      // getBar with arg "1" has been called twice

// Reset mock
resetCalls(mockedFoo);

// Call count verification
verify(mockedFoo.getBar(1)).never();      // has never been called after reset

You can also reset calls of multiple mocks at once resetCalls(firstMock, secondMock, thirdMock)

Resetting mock

Or reset mock call counter with all stubs

// Creating mock
let mockedFoo:Foo = mock(Foo);
when(mockedFoo.getBar(1)).thenReturn("one").

// Getting instance
let foo:Foo = instance(mockedFoo);

// Some calls
console.log(foo.getBar(1));               // "one" - as defined in stub
console.log(foo.getBar(1));               // "one" - as defined in stub
verify(mockedFoo.getBar(1)).twice();      // getBar with arg "1" has been called twice

// Reset mock
reset(mockedFoo);

// Call count verification
verify(mockedFoo.getBar(1)).never();      // has never been called after reset
console.log(foo.getBar(1));               // null - previously added stub has been removed

You can also reset multiple mocks at once reset(firstMock, secondMock, thirdMock)

Capturing method arguments

let mockedFoo:Foo = mock(Foo);
let foo:Foo = instance(mockedFoo);

// Call method
foo.sumTwoNumbers(1, 2);

// Check first arg captor values
const [firstArg, secondArg] = capture(mockedFoo.sumTwoNumbers).last();
console.log(firstArg);    // prints 1
console.log(secondArg);    // prints 2

You can also get other calls using first(), second(), byCallIndex(3) and more...

Recording multiple behaviors

You can set multiple returning values for same matching values

const mockedFoo:Foo = mock(Foo);

when(mockedFoo.getBar(anyNumber())).thenReturn('one').thenReturn('two').thenReturn('three');

const foo:Foo = instance(mockedFoo);

console.log(foo.getBar(1));    // one
console.log(foo.getBar(1));    // two
console.log(foo.getBar(1));    // three
console.log(foo.getBar(1));    // three - last defined behavior will be repeated infinitely

Another example with specific values

let mockedFoo:Foo = mock(Foo);

when(mockedFoo.getBar(1)).thenReturn('one').thenReturn('another one');
when(mockedFoo.getBar(2)).thenReturn('two');

let foo:Foo = instance(mockedFoo);

console.log(foo.getBar(1));    // one
console.log(foo.getBar(2));    // two
console.log(foo.getBar(1));    // another one
console.log(foo.getBar(1));    // another one - this is last defined behavior for arg '1' so it will be repeated
console.log(foo.getBar(2));    // two
console.log(foo.getBar(2));    // two - this is last defined behavior for arg '2' so it will be repeated

Short notation:

const mockedFoo:Foo = mock(Foo);

// You can specify return values as multiple thenReturn args
when(mockedFoo.getBar(anyNumber())).thenReturn('one', 'two', 'three');

const foo:Foo = instance(mockedFoo);

console.log(foo.getBar(1));    // one
console.log(foo.getBar(1));    // two
console.log(foo.getBar(1));    // three
console.log(foo.getBar(1));    // three - last defined behavior will be repeated infinity

Possible errors:

const mockedFoo:Foo = mock(Foo);

// When multiple matchers, matches same result:
when(mockedFoo.getBar(anyNumber())).thenReturn('one');
when(mockedFoo.getBar(3)).thenReturn('one');

const foo:Foo = instance(mockedFoo);
foo.getBar(3); // MultipleMatchersMatchSameStubError will be thrown, two matchers match same method call

Mocking interfaces

You can mock interfaces too, just instead of passing type to mock function, set mock function generic type Mocking interfaces requires Proxy implementation

let mockedFoo:Foo = mock<FooInterface>(); // instead of mock(FooInterface)
const foo: SampleGeneric<FooInterface> = instance(mockedFoo);

Mocking types

You can mock abstract classes

const mockedFoo: SampleAbstractClass = mock(SampleAbstractClass);
const foo: SampleAbstractClass = instance(mockedFoo);

You can also mock generic classes, but note that generic type is just needed by mock type definition

const mockedFoo: SampleGeneric<SampleInterface> = mock(SampleGeneric);
const foo: SampleGeneric<SampleInterface> = instance(mockedFoo);

Spying on real objects

You can partially mock an existing instance:

const foo: Foo = new Foo();
const spiedFoo = spy(foo);

when(spiedFoo.getBar(3)).thenReturn('one');

console.log(foo.getBar(3)); // 'one'
console.log(foo.getBaz()); // call to a real method

You can spy on plain objects too:

const foo = { bar: () => 42 };
const spiedFoo = spy(foo);

foo.bar();

console.log(capture(spiedFoo.bar).last()); // [42] 

Thanks


Download Details:

Author: NagRock
Source Code: https://github.com/NagRock/ts-mockito 
License: MIT license

#typescript #testing #mock 

NBB: Ad-hoc CLJS Scripting on Node.js

Nbb

Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.

Status

Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.

Requirements

Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).

Usage

Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'
6

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs

Macros

Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)
                                        body))))
            body
            binding-pairs)))

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.

Dependencies

NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.

Classpath

To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"

Reagent

Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink

ink-demo.cljs:

(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))

Promesa

Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
  (js/Promise.
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
  []
  (p/do!
   (println "Doing stuff which takes a while")
   (sleep 1000)
   1))

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3

Also see API docs.

Js-interop

Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.

Examples

See the examples directory for small examples.

Also check out these projects built with nbb:

API

See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.

Build

Prequisites:

  • babashka >= 0.4.0
  • Clojure CLI >= 1.10.3.933
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

Leonard  Paucek

Leonard Paucek

1656280800

Jump to Local IDE Code Directly From Browser React Component

React Dev Inspector

Jump to local IDE code directly from browser React component by just a simple click

This package allows users to jump to local IDE code directly from browser React component by just a simple click, which is similar to Chrome inspector but more advanced.

View Demo View Github

Preview

press hotkey (ctrl⌃ + shift⇧ + commmand⌘ + c), then click the HTML element you wish to inspect.

screen record gif (8M size):

Jump to local IDE code directly from browser React component by just a simple click

Installation

npm i -D react-dev-inspector

Usage

Users need to add React component and apply webpack config before connecting your React project with 'react-dev-inspector'.

Note: You should NOT use this package, and React component, webpack config in production mode


 

1. Add Inspector React Component

import React from 'react'
import { Inspector, InspectParams } from 'react-dev-inspector'

const InspectorWrapper = process.env.NODE_ENV === 'development'
  ? Inspector
  : React.Fragment

export const Layout = () => {
  // ...

  return (
     {}}
      onClickElement={(params: InspectParams) => {}}
    >
     
       ...
     
    
  )
}


 

2. Set up Inspector Config

You should add:

  • an inspector babel plugin, to inject source code location info
    • react-dev-inspector/plugins/babel
  • an server api middleware, to open local IDE
    • import { launchEditorMiddleware } from 'react-dev-inspector/plugins/webpack'

to your current project development config.

Such as add babel plugin into your .babelrc or webpack babel-loader config,
add api middleware into your webpack-dev-server config or other server setup.


 

There are some example ways to set up, please pick the one fit your project best.

In common cases, if you're using webpack, you can see #raw-webpack-config,

If your project happen to use vite / nextjs / create-react-app and so on, you can also try out our integrated plugins / examples with

raw webpack config

Example:

// .babelrc.js
module.exports = {
  plugins: [
    /**
     * react-dev-inspector plugin, options docs see:
     * https://github.com/zthxxx/react-dev-inspector#inspector-babel-plugin-options
     */
    'react-dev-inspector/plugins/babel',
  ],
}
// webpack.config.ts
import type { Configuration } from 'webpack'
import { launchEditorMiddleware } from 'react-dev-inspector/plugins/webpack'

const config: Configuration = {
  /**
   * [server side] webpack dev server side middleware for launch IDE app
   */
  devServer: {
    before: (app) => {
      app.use(launchEditorMiddleware)
    },
  },
}


 

usage with Vite2

example project see: https://github.com/zthxxx/react-dev-inspector/tree/master/examples/vite2

example vite.config.ts:

import { defineConfig } from 'vite'
import { inspectorServer } from 'react-dev-inspector/plugins/vite'

export default defineConfig({
  plugins: [
    inspectorServer(),
  ],
})


 

usage with Next.js

use Next.js Custom Server + Customizing Babel Config

example project see: https://github.com/zthxxx/react-dev-inspector/tree/master/examples/nextjs

in server.js, example:

...

const {
  queryParserMiddleware,
  launchEditorMiddleware,
} = require('react-dev-inspector/plugins/webpack')

app.prepare().then(() => {
  createServer((req, res) => {
    /**
     * middlewares, from top to bottom
     */
    const middlewares = [
      /**
       * react-dev-inspector configuration two middlewares for nextjs
       */
      queryParserMiddleware,
      launchEditorMiddleware,

      /** Next.js default app handle */
        (req, res) => handle(req, res),
    ]

    const middlewarePipeline = middlewares.reduceRight(
      (next, middleware) => (
        () => { middleware(req, res, next) }
      ),
      () => {},
    )

    middlewarePipeline()

  }).listen(PORT, (err) => {
    if (err) throw err
    console.debug(`> Ready on http://localhost:${PORT}`)
  })
})

in package.json, example:

  "scripts": {
-    "dev": "next dev",
+    "dev": "node server.js",
    "build": "next build"
  }

in .babelrc.js, example:

module.exports = {
  plugins: [
    /**
     * react-dev-inspector plugin, options docs see:
     * https://github.com/zthxxx/react-dev-inspector#inspector-babel-plugin-options
     */
    'react-dev-inspector/plugins/babel',
  ],
}


 

usage with create-react-app

cra + react-app-rewired + customize-cra example config-overrides.js:

example project see: https://github.com/zthxxx/react-dev-inspector/tree/master/examples/cra

const { ReactInspectorPlugin } = require('react-dev-inspector/plugins/webpack')
const {
  addBabelPlugin,
  addWebpackPlugin,
} = require('customize-cra')

module.exports = override(
  addBabelPlugin([
    'react-dev-inspector/plugins/babel',
    // plugin options docs see:
    // https://github.com/zthxxx/react-dev-inspector#inspector-babel-plugin-options
    {
      excludes: [
        /xxxx-want-to-ignore/,
      ],
    },
  ]),
  addWebpackPlugin(
    new ReactInspectorPlugin(),
  ),
)


 

usage with Umi3

example project see: https://github.com/zthxxx/react-dev-inspector/tree/master/examples/umi3

Example .umirc.dev.ts:

// https://umijs.org/config/
import { defineConfig } from 'umi'

export default defineConfig({
  plugins: [
    'react-dev-inspector/plugins/umi/react-inspector',
  ],
  inspectorConfig: {
    // babel plugin options docs see:
    // https://github.com/zthxxx/react-dev-inspector#inspector-babel-plugin-options
    excludes: [],
  },
})


 

usage with Umi2

Example .umirc.dev.js:

import { launchEditorMiddleware } from 'react-dev-inspector/plugins/webpack'

export default {
  // ...
  extraBabelPlugins: [
    // plugin options docs see:
    // https://github.com/zthxxx/react-dev-inspector#inspector-babel-plugin-options
    'react-dev-inspector/plugins/babel',
  ],

  /**
   * And you need to set `false` to `dll` in `umi-plugin-react`,
   * becase these is a umi2 bug that `dll` cannot work with `devServer.before`
   *
   * https://github.com/umijs/umi/issues/2599
   * https://github.com/umijs/umi/issues/2161
   */
  chainWebpack(config, { webpack }) {
    const originBefore = config.toConfig().devServer

    config.devServer.before((app, server, compiler) => {
      
      app.use(launchEditorMiddleware)
      
      originBefore?.before?.(app, server, compiler)
    })

    return config  
  },
}

usage with Ice.js

Example build.json:

// https://ice.work/docs/guide/basic/build
{
  "plugins": [
    "react-dev-inspector/plugins/ice",
  ]
}


 

Examples Project Code


 

Configuration

Component Props

checkout TS definition under react-dev-inspector/es/Inspector.d.ts.

PropertyDescriptionTypeDefault
keysinspector hotkeys

supported keys see: https://github.com/jaywcjlove/hotkeys#supported-keys
string[]['control', 'shift', 'command', 'c']
disableLaunchEditordisable editor launching

(launch by default in dev Mode, but not in production mode)
booleanfalse
onHoverElementtriggered when mouse hover in inspector mode(params: InspectParams) => void-
onClickElementtriggered when mouse hover in inspector mode(params: InspectParams) => void-
// import type { InspectParams } from 'react-dev-inspector'

interface InspectParams {
  /** hover / click event target dom element */
  element: HTMLElement,
  /** nearest named react component fiber for dom element */
  fiber?: React.Fiber,
  /** source file line / column / path info for react component */
  codeInfo?: {
    lineNumber: string,
    columnNumber: string,
    /**
    * code source file relative path to dev-server cwd(current working directory)
    * need use with `react-dev-inspector/plugins/babel`
    */
    relativePath?: string,
    /**
    * code source file absolute path
    * just need use with `@babel/plugin-transform-react-jsx-source` which auto set by most framework
    */
    absolutePath?: string,
  },
  /** react component name for dom element */
  name?: string,
}


 

Inspector Babel Plugin Options

interface InspectorPluginOptions {
  /** override process.cwd() */
  cwd?: string,
  /** patterns to exclude matched files */
  excludes?: (string | RegExp)[],
}


 

Inspector Loader Props

// import type { ParserPlugin, ParserOptions } from '@babel/parser'
// import type { InspectorConfig } from 'react-dev-inspector/plugins/webpack'

interface InspectorConfig {
  /** patterns to exclude matched files */
  excludes?: (string | RegExp)[],
  /**
   * add extra plugins for babel parser
   * default is ['typescript', 'jsx', 'decorators-legacy', 'classProperties']
   */
  babelPlugins?: ParserPlugin[],
  /** extra babel parser options */
  babelOptions?: ParserOptions,
}


 

IDE / Editor config

This package uses react-dev-utils to launch your local IDE application, but, which one will be open?

In fact, it uses an environment variable named REACT_EDITOR to specify an IDE application, but if you do not set this variable, it will try to open a common IDE that you have open or installed once it is certified.

For example, if you want it always open VSCode when inspection clicked, set export REACT_EDITOR=code in your shell.


 

VSCode

install VSCode command line tools, see the official docs
install-vscode-cli

set env to shell, like .bashrc or .zshrc

export REACT_EDITOR=code


 

WebStorm

  • just set env with an absolute path to shell, like .bashrc or .zshrc (only MacOS)
export REACT_EDITOR='/Applications/WebStorm.app/Contents/MacOS/webstorm'

OR

install WebStorm command line tools
Jump to local IDE code directly from browser React component by just a simple click

then set env to shell, like .bashrc or .zshrc

export REACT_EDITOR=webstorm


 

Vim

Yes! you can also use vim if you want, just set env to shell

export REACT_EDITOR=vim


 

How It Works

Stage 1 - Compile Time

  • [babel plugin] inject source file path/line/column to JSX data attributes props

Stage 2 - Web React Runtime

[React component] Inspector Component in react, for listen hotkeys, and request api to dev-server for open IDE.

Specific, when you click a component DOM, the Inspector will try to obtain its source file info (path/line/column), then request launch-editor api (in stage 3) with absolute file path.

Stage 3 - Dev-server Side

[middleware] setup launchEditorMiddleware in webpack dev-server (or other dev-server), to open file in IDE according to the request params.

Only need in development mode,and you want to open IDE when click a component element.

Not need in prod mode, or you just want inspect dom without open IDE (set disableLaunchEditor={true} to Inspector component props)

Analysis of Theory


Author: zthxxx
Source code: https://github.com/zthxxx/react-dev-inspector
License: MIT license

#react-native #react 

Aria Barnes

Aria Barnes

1622719015

Why use Node.js for Web Development? Benefits and Examples of Apps

Front-end web development has been overwhelmed by JavaScript highlights for quite a long time. Google, Facebook, Wikipedia, and most of all online pages use JS for customer side activities. As of late, it additionally made a shift to cross-platform mobile development as a main technology in React Native, Nativescript, Apache Cordova, and other crossover devices. 

Throughout the most recent couple of years, Node.js moved to backend development as well. Designers need to utilize a similar tech stack for the whole web project without learning another language for server-side development. Node.js is a device that adjusts JS usefulness and syntax to the backend. 

What is Node.js? 

Node.js isn’t a language, or library, or system. It’s a runtime situation: commonly JavaScript needs a program to work, however Node.js makes appropriate settings for JS to run outside of the program. It’s based on a JavaScript V8 motor that can run in Chrome, different programs, or independently. 

The extent of V8 is to change JS program situated code into machine code — so JS turns into a broadly useful language and can be perceived by servers. This is one of the advantages of utilizing Node.js in web application development: it expands the usefulness of JavaScript, permitting designers to coordinate the language with APIs, different languages, and outside libraries.

What Are the Advantages of Node.js Web Application Development? 

Of late, organizations have been effectively changing from their backend tech stacks to Node.js. LinkedIn picked Node.js over Ruby on Rails since it took care of expanding responsibility better and decreased the quantity of servers by multiple times. PayPal and Netflix did something comparative, just they had a goal to change their design to microservices. We should investigate the motivations to pick Node.JS for web application development and when we are planning to hire node js developers. 

Amazing Tech Stack for Web Development 

The principal thing that makes Node.js a go-to environment for web development is its JavaScript legacy. It’s the most well known language right now with a great many free devices and a functioning local area. Node.js, because of its association with JS, immediately rose in ubiquity — presently it has in excess of 368 million downloads and a great many free tools in the bundle module. 

Alongside prevalence, Node.js additionally acquired the fundamental JS benefits: 

  • quick execution and information preparing; 
  • exceptionally reusable code; 
  • the code is not difficult to learn, compose, read, and keep up; 
  • tremendous asset library, a huge number of free aides, and a functioning local area. 

In addition, it’s a piece of a well known MEAN tech stack (the blend of MongoDB, Express.js, Angular, and Node.js — four tools that handle all vital parts of web application development). 

Designers Can Utilize JavaScript for the Whole Undertaking 

This is perhaps the most clear advantage of Node.js web application development. JavaScript is an unquestionable requirement for web development. Regardless of whether you construct a multi-page or single-page application, you need to know JS well. On the off chance that you are now OK with JavaScript, learning Node.js won’t be an issue. Grammar, fundamental usefulness, primary standards — every one of these things are comparable. 

In the event that you have JS designers in your group, it will be simpler for them to learn JS-based Node than a totally new dialect. What’s more, the front-end and back-end codebase will be basically the same, simple to peruse, and keep up — in light of the fact that they are both JS-based. 

A Quick Environment for Microservice Development 

There’s another motivation behind why Node.js got famous so rapidly. The environment suits well the idea of microservice development (spilling stone monument usefulness into handfuls or many more modest administrations). 

Microservices need to speak with one another rapidly — and Node.js is probably the quickest device in information handling. Among the fundamental Node.js benefits for programming development are its non-obstructing algorithms.

Node.js measures a few demands all at once without trusting that the first will be concluded. Many microservices can send messages to one another, and they will be gotten and addressed all the while. 

Versatile Web Application Development 

Node.js was worked in view of adaptability — its name really says it. The environment permits numerous hubs to run all the while and speak with one another. Here’s the reason Node.js adaptability is better than other web backend development arrangements. 

Node.js has a module that is liable for load adjusting for each running CPU center. This is one of numerous Node.js module benefits: you can run various hubs all at once, and the environment will naturally adjust the responsibility. 

Node.js permits even apportioning: you can part your application into various situations. You show various forms of the application to different clients, in light of their age, interests, area, language, and so on. This builds personalization and diminishes responsibility. Hub accomplishes this with kid measures — tasks that rapidly speak with one another and share a similar root. 

What’s more, Node’s non-hindering solicitation handling framework adds to fast, letting applications measure a great many solicitations. 

Control Stream Highlights

Numerous designers consider nonconcurrent to be one of the two impediments and benefits of Node.js web application development. In Node, at whatever point the capacity is executed, the code consequently sends a callback. As the quantity of capacities develops, so does the number of callbacks — and you end up in a circumstance known as the callback damnation. 

In any case, Node.js offers an exit plan. You can utilize systems that will plan capacities and sort through callbacks. Systems will associate comparable capacities consequently — so you can track down an essential component via search or in an envelope. At that point, there’s no compelling reason to look through callbacks.

 

Final Words

So, these are some of the top benefits of Nodejs in web application development. This is how Nodejs is contributing a lot to the field of web application development. 

I hope now you are totally aware of the whole process of how Nodejs is really important for your web project. If you are looking to hire a node js development company in India then I would suggest that you take a little consultancy too whenever you call. 

Good Luck!

Original Source

#node.js development company in india #node js development company #hire node js developers #hire node.js developers in india #node.js development services #node.js development

Vincent Lab

Vincent Lab

1605177692

How to Use Template Engines for Beginners in Node.js

In this video, I will be showing you what a templating engine is by showing you 3 different templating engines the ones we will look at it is pug, mustache and ejs.

#node js tutorial #node js templating #node js templates #nodejs for beginners #mustache templating #mustache.js