<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrea Sonny on Medium]]></title>
        <description><![CDATA[Stories by Andrea Sonny on Medium]]></description>
        <link>https://medium.com/@andreasonny83?source=rss-38c2afea51f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*otpAapVdj7irik5rrV0MlQ.jpeg</url>
            <title>Stories by Andrea Sonny on Medium</title>
            <link>https://medium.com/@andreasonny83?source=rss-38c2afea51f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:25:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andreasonny83/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Automate your deployments of AWS Lambda functions with CircleCI]]></title>
            <link>https://medium.com/a-cloud-guru/continuous-deployment-with-serverless-and-circleci-772f990820ee?source=rss-38c2afea51f------2</link>
            <guid isPermaLink="false">https://medium.com/p/772f990820ee</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Andrea Sonny]]></dc:creator>
            <pubDate>Sat, 24 Feb 2018 14:22:55 GMT</pubDate>
            <atom:updated>2018-03-08T19:30:37.732Z</atom:updated>
            <content:encoded><![CDATA[<h4>Stop wasting your time and money with manual code deploys</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hSKKzXZsnHOYwi21yxwJCA.png" /></figure><p>A lot of companies are still struggling to achieve a smooth and efficient deployment workflow. <em>Why?</em> Because teams are overly focused on development activities without regard to maturing their deployment process.</p><p>What’s the point of using new serverless technologies like AWS Lambda if you still need to manually run all your tests prior to deploying your functions?</p><p>It sounds crazy — but people don’t realize how much money they are loosing just because of the time and resources spent with manual processes. If you can automate your deployment process, then you can focus on developing product features instead of wasting time manually testing and releasing new code.</p><p>So why should you build a continuous integration and deployment architecture ? Because you shouldn’t be spending a lot of time and resources on manual and inefficient processes that can be easily automated.</p><p>I’m going to show you how easy it is to automate serverless deployments. For this example, we be using a simple “hello world” application I created which returns a random string using an NodeJS module <a href="https://nodei.co/npm/unique-names-generator/">that I published to npm</a>.</p><h4>Let’s get started!</h4><p>For this project, we’re going to use NodeJS and the <a href="https://serverless.com/">Serverless framework</a>. To begin, create a new folder on your desktop. Then open a terminal to your new project’s directory and type:</p><pre>$ npm init</pre><p>Press enter to all the questions to initialize your new Node project. Then install the Serverless Framework with the following command:</p><pre>$ npm i -D serverless serverless-offline</pre><p>We’re going to use Serverless to build all the infrastructure needed, and then deploy our application into an AWS Lambda function. Serverless-offline will be used to run and test our function locally.</p><p>For this project, we’re going to use one dependency for generating the unique names that will used by our function. We can install the following package as a project dependency using the following command:</p><pre>$ npm i -S unique-names-generator</pre><h4>Testing our code with Jest</h4><p>First we’ll automate the testing process to verify any new code being added to our project. Then we’re going to create a continuous integration (CI) system that prevents the deployment of broken code to our live environment.</p><p>Let’s install Jest for testing our code. <em>Why Jest? </em>Jest is an solid testing tool developed by Facebook that requires zero configuration — so you can start writing tests out-of-the-box without wasting time on tedious configuration.</p><pre>$ nmp i -D jest</pre><p>Now let’s write a simple tests for the new function.</p><p>Just create a file called handler.test.js in your project’s folder — assuming that our function will reside in a file called handler.js.</p><pre>const { handler } = require(&#39;./handler&#39;);</pre><pre>jest.mock(&#39;unique-names-generator&#39;,<br>() =&gt; ({<br>  generate: jest.fn().mockImplementation(() =&gt; &#39;mocked-name&#39;),<br>}));</pre><pre>describe(&#39;handler&#39;, () =&gt; {<br>  test(&#39;the handler function should work&#39;, () =&gt; {<br>    handler({}, {}, (err, response) =&gt; {<br>      expect(err).toBeNull();<br>      expect(response).toBeDefined();<br>    });<br>  });</pre><pre>test(&#39;the response should be successful&#39;, () =&gt; {<br>    handler({}, {}, (err, response) =&gt; {<br>      expect(response.statusCode).toEqual(200);<br>    });<br>  });</pre><pre>test(&#39;the response should contain a `name` key&#39;, () =&gt; {       <br>    handler({}, {}, (err, response) =&gt; {<br>      expect(response).toMatchSnapshot();<br>    });<br>  });<br>});</pre><p>Now create a test script in your package.json file so we can run our tests:</p><pre>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;jest&quot;<br>}</pre><p>Since we haven’t created our handler.js module yet, running npm test is going to fail at this point — so let’s create our module.</p><h4>Developing the function</h4><p>For next steps, let’s create our basic handler.js file:</p><pre>const { generate } = require(&#39;unique-names-generator&#39;);</pre><pre>exports.handler = (event, context, callback) =&gt; {<br>  const response = {<br>    statusCode: 200,<br>    body: JSON.stringify({<br>      name: generate(),<br>    }),<br>  };</pre><pre>callback(null, response);<br>};</pre><p>The code is extremely simple. We’re just returning a JSON response with a random name created by the unique-names-generator module.</p><h4>Deploying our function</h4><p>We’re almost ready to deploy our function! If we execute our tests now, Jest should now reward us with a green successful test result.</p><p>We can test the logic in our local environment using serverless-offline. For next steps, simply setup the Serverless configuration file required for deploying our Lambda function.</p><p>Now just create the following serverless.yml file inside our project folder:</p><pre>service: serverless-name-generator</pre><pre>provider:<br>  name: aws<br>  runtime: nodejs6.10</pre><pre>plugins:<br>  - serverless-offline</pre><pre>functions:<br>  generate:<br>    handler: handler.handler # required, handler set in AWS Lambda<br>    events:<br>      - http:<br>          path: generate<br>          method: get</pre><p>To server the Lambda function using the serverless-offline plugin, we need to implement a new script in our package.json file:</p><pre>&quot;script&quot;: {<br>  &quot;serve&quot;: &quot;serverless offline start&quot;,<br>  ...</pre><p>Now bootstrap your local server with npm run serve command, and you should receive the following message:</p><pre>Serverless: Starting Offline: dev/us-east-1.</pre><pre>Serverless: Routes for generate:<br>Serverless: GET /generate</pre><pre>Serverless: Offline listening on <a href="http://localhost:3000/">http://localhost:3000</a></pre><p>This message means that you can now open a browser to <a href="http://localhost:3000/generate">http://localhost:3000/generate</a> to enjoy your unique name!</p><p>The response generated should look something like this:</p><pre><strong>{<br>  </strong>&quot;name&quot;: &quot;angry_green_alpaca&quot;<br><strong>}</strong></pre><p>You can see a live version of this code running here: <a href="https://gu9294gok9.execute-api.us-east-1.amazonaws.com/dev/generate">https://gu9294gok9.execute-api.us-east-1.amazonaws.com/dev/generate</a></p><h4>Automating deployments with CircleCI</h4><p>The last step is deploying our code — while ensuring that the newer version is always tested and deployed <em>automatically </em>with CircleCI.</p><p><a href="https://circleci.com/">CircleCI </a>is cloud based solution to automate your development process — it’s very quick and efficient. You can register for a new account using your GitHub account — then just click on the Add projects section.</p><p>While you’ll be able to see your GitHub repository, you won’t be able to link it to CircleCI at this point. First, you’ll need to push a CircleCI configuration file to your GitHub repository.</p><ul><li>Inside your project directory, create a new folder called .circleci</li><li>Now create a config.yml file inside with the following configuration:</li></ul><pre>version: 2</pre><pre>jobs:<br>  build:</pre><pre>docker:<br>      - image: circleci/node:8</pre><pre>working_directory: ~/repo</pre><pre>steps:<br>      - checkout</pre><pre>- run:<br>          name: Install Node dependencies<br>          command: npm install</pre><pre>- run:<br>          name: Unit tests<br>          command: npm test</pre><pre>- run:<br>          name: Deploy to AWS<br>          command: npm run deploy</pre><p>This file informs CircleCI to use NodeJS version 8 for running our Jest tests and, if the tests are passing, deploy our application.</p><p>Now let’s push our new file to our Git repo!</p><pre>$ git add .<br>$ git commit -m &quot;CircleCI configuration&quot;<br>$ git push origin master</pre><p>If you go back to your CircleCI dashboard to the Add projects section — you should be able to click and enter inside your new project repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8W_q4iSZzMIVVo6DwR0WQ.png" /></figure><p>A new build should be automatically be triggered — and it should fail since we’re currently missing a deploy script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYUnt3c7BAvwuuxAZoABUA.png" /></figure><h4>AWS CodeDeploy</h4><p>CircleCI comes with native AWS support. Everything we need for setup can be found inside our project’s settings — simply click on the cog next to our project’s name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*niHVnL15BOT9NNblzPRJQw.png" /></figure><p>One the left-side of the navigation bar under the Continuous Deployment section, you’ll find an option for AWS CodeDeploy.</p><p><strong>Creating an AWS user for CircleCI<br></strong>The first step is entering your AWS information in the form. I would recommend logging into the AWS Console and creating a CircleCI user to assign to CircleCI projects. If you don’t have an AWS account, be sure to leverage their <a href="https://aws.amazon.com/free/">free tier.</a></p><p>To create a new user for your CI/CD, access your <a href="https://console.aws.amazon.com/iam/">IAM settings from your AWS dashboard</a>, click Users and then Add User.</p><ul><li>Tick the “programmatic access” checkbox and create a meaningful name for your new user (eg. circleci-user).</li><li>On the next screen (permissions), select the “attach existing policies directly” and check the AdministratorAccess from the list.</li><li>Now you should be able to see your new account Key and Secret for the new user. Paste those keys in the CircleCI settings page then click Save AWS Keys.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NIFobyMOoVhtWVd90JuyTw.png" /><figcaption>AWS CodeDeploy settings page</figcaption></figure><p>Your CircleCI job now has all the administrative access required to deploy your AWS Lambda function.</p><h4>Automated serverless deployments!</h4><p>The missing piece of the puzzle is the deployment script required for CircleCI to push your code into a new Lambda function hosted on AWS.</p><p>For this final piece, just add a new script to your package.json file:</p><pre>&quot;scripts&quot;: {<br>  &quot;deploy&quot;: &quot;serverless deploy&quot;<br>  ...</pre><p>That’s it — seriously!</p><p>Now just push this small change to your GitHub repository and watch CircleCI deploy your Lambda function for you — after, of course, all the test are finished and green.</p><p>Once the job is done, you can copy and paste the endpoint provided under the “Deploy application” task into a new browser tab and enjoy your Lambda function.</p><p>Going forward, CircleCI will run the unit tests and then publish a new version of your application in just a couple of minutes — every time any new code is pushed to your Git repository!</p><h4>Thanks for reading</h4><p>Now you can just stay focused on developing code for new product features — and stop wasting valuable time and money on manual deployment processes.</p><p>For reference, here’s the <a href="https://github.com/andreasonny83/serverless-name-generator.git">GitHub repository</a> where I pushed all the code I mentioned in this article — and more. I hope you found this interesting and useful. If you have any comment or have spotted any mistake, please leave a message in the comments.</p><p><em>Thanks for reading!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=772f990820ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/a-cloud-guru/continuous-deployment-with-serverless-and-circleci-772f990820ee">Automate your deployments of AWS Lambda functions with CircleCI</a> was originally published in <a href="https://medium.com/a-cloud-guru">A Cloud Guru</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a serverless app for on-demand image processing]]></title>
            <link>https://medium.com/a-cloud-guru/serverless-image-optimization-and-delivery-510b6c311fe5?source=rss-38c2afea51f------2</link>
            <guid isPermaLink="false">https://medium.com/p/510b6c311fe5</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Andrea Sonny]]></dc:creator>
            <pubDate>Sat, 03 Feb 2018 17:08:43 GMT</pubDate>
            <atom:updated>2018-03-04T05:16:32.343Z</atom:updated>
            <content:encoded><![CDATA[<h4>Develop an on-demand serverless app that updates the scale, quality, and format of an image from your browser</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJTZvxnViljJdXZ7WjEfDQ.png" /></figure><p>I’ve been exploring AWS Lambda functions for a couple of months — and I’m starting to see the huge benefits of building small serverless applications.</p><p>First of all, you don’t need a server — obviously. The problem with creating server side applications has always been the cost of maintaining a server that deploys and hosts my application, and paying for idle resources while waiting for someone to interact with them.</p><p>Of course, you can find free NodeJS hosting providers around the web like Heroku — but you’ll be faced with account restrictions, can’t really deploy hundreds of small micro-services, and won’t be charged only for real usage.</p><p>Here is where AWS Lambda comes to the rescue.</p><ol><li>You can deploy as many Lambda functions as you want — and basically for free using the AWS free tier account.</li><li>You are charged only for the real usage of your functions — without the need of maintaining and paying for an entire server</li></ol><p>Another interesting advantage is speed. Lambda functions are executed in an incredibly fast amount of time — normally between 100 and 500ms.</p><p>Unlike using Docker, you’ll never have to wait for the virtual environment to be bootstrapped for your code to be executed. Using Lambda functions is really like having a very powerful server machine always up and running — but without the cost.</p><p>With the <a href="https://aws.amazon.com/lambda/pricing/">AWS free tier account</a>, you get 400,000 seconds of Lambda execution per month <em>completely for free</em>. Based on an average of 500ms per lambda invocation, it means that you can invoke your functions 800,000 times/month completely free of charge. Not bad at all.</p><h4>Creating a serverless app for image optimization</h4><p>My need was to create a NodeJS application responsible for delivering images to my client application.</p><p>The app needs the ability to automatically scale my images up and down according to the client’s screen size — so I can avoid creating and storing multiple variations of the same images required for mobile, tablet and desktop versions. The quality and format of the image needs to be changed on demand — also without needing to store all the different images</p><p>This seemed like a perfect job for using AWS Lambda functions.</p><h4>Setup of NodeJS</h4><p>My first step was to setup NodeJS so I could test my code locally and not have to redeploy my code every time I wanted to validate changes. To get going, start by creating a new folder on your local machine to host the new project.</p><pre>$ mkdir serverless-image-rendering &amp;&amp; cd $_</pre><p>Then initialize a new npm project and press enter to accept the defaults.</p><pre>$ npm init</pre><p>Now we’re going to create an old school Express app to listen on your local port 3000. So create a new app.js file and paste the following code inside:</p><pre>const app = require(&#39;express&#39;)();<br>const bodyParser = require(&#39;body-parser&#39;);<br>const PORT = 3000;</pre><pre>app.use(bodyParser.json());</pre><pre>const displayStatus = () =&gt; ({<br>  status: `OK`, });</pre><pre>app.get(&#39;/status&#39;, (req, res) =&gt; {<br>  res.status(200).send(displayStatus());<br>});</pre><pre>const server = app.listen(PORT, () =&gt;<br>  console.log(&#39;Listening on &#39; +<br>    `<a href="http://localhost:${server.address().port}`">http://localhost:${server.address().port}`</a>));</pre><p>For this app, we’re going to need 2 npm packages Express and body-parser .<br>This 2 packages will only be required for testing your app locally, so we’re going to install them in your development dependencies — this will avoid them be including in your Lambda function.</p><pre>$ npm i -D express body-parser</pre><p>I normally also install nodemon globally on my machine — it monitors any file changes which will automatically restart the app.</p><pre>$ npm i -g nodemon</pre><p>Then you can bootstrap your local server application:</p><pre>$ nodemon app.js</pre><p>You should now be able to open your browser to <a href="http://localhost:3000/status">http://localhost:3000/status</a> and be able to see a &quot;status&quot;: &quot;OK&quot; message.</p><h4>How to fetch your images from S3</h4><p>I like to use S3 to store all the images, and have the function fetch an image from the S3 bucket for resizing and delivery to the client app.So I’m going to use AWS to create an S3 bucket and name it images-bucket.</p><p>Then I will need an image-fetcher class to open my S3 bucket, find my target image, and return it back to my app. To do this, simply create a image-fetcher.js inside a src folder and paste the following code inside:</p><pre>const AWS = require(&#39;aws-sdk&#39;);</pre><pre>const getS3 = (s3, bucketName, fileName) =&gt;<br>new Promise((res, rej) =&gt; {<br>  s3.getObject({<br>    Bucket: bucketName,<br>    Key: fileName<br>  }, <br>  (err, data) =&gt; {<br>    if (err) {<br>      return rej(err);<br>    }</pre><pre>    const contentType = data.ContentType;<br>    const image = data.Body;</pre><pre>    return res({ image, contentType });<br>  });<br>});</pre><pre>class ImageFetcher {<br>  constructor(bucketName) {<br>    this.S3 = new AWS.S3();<br>    this.bucketName = bucketName;<br>  }</pre><pre>  fetchImage(fileName) {<br>    if (!fileName) {<br>      return Promise.reject(&#39;Filename not specified&#39;);<br>    }</pre><pre>  return Promise.resolve(<br>    getS3(this.S3, this.bucketName, fileName)));<br>  }<br>}</pre><pre>module.exports = ImageFetcher;</pre><p>This ImageFetcher class will attempt to read a file stored inside the bucketName and return the image if found.</p><p>Ok, now we can set our app.js file to consume this class for fetching and delivering an image to the browser. So, let’s create a /fetch-image endpoint!</p><pre>// app.js<br>const ImageFetcher = require(&#39;./src/image-fetcher&#39;);<br>...<br>app.get(&#39;/fetch-image&#39;, (req, res) =&gt; {<br>  const imageFetcher = new ImageFetcher(process.env.BUCKET);<br>  const fileName = req.query &amp;&amp; req.query.f;</pre><pre>  return imageFetcher<br>    .fetchImage(fileName)<br>    .then(data =&gt; {<br>      const img = new Buffer(data.image.buffer, &#39;base64&#39;);<br>      res.writeHead(200, {<br>        &#39;Content-Type&#39;: data.contentType<br>      });<br>      res.end(img);<br>    })<br>    .catch(error =&gt; {<br>      console.error(error);<br>      res.status(400).send(error.message || error);<br>    });<br>});</pre><p>Now you should be able to fetch and display an image present inside your previously created images-bucket S3 bucket.</p><p>Note that we’re passing a process.env.BUCKET variable into our ImageFetcher constructor. This variable is fetched from your system environment variables — so we’ll need to manually pass that variable to our application. From now on, on our terminal we’ll need to launch our app.js file in this manner:</p><pre>$ BUCKET=images-bucket nodemon app.js</pre><p>This will make sure that a BUCKET environment variable will be present and set to our S3 bucket name.</p><p>Now we can open a browser to our new endpoint called <a href="http://localhost:3000/fetch-image">http://localhost:3000/fetch-image</a> and pass a file name as a query string — although we don’t have any image in our bucket at the moment.</p><p>Manually upload a new image called sample.jpg inside your images-bucket and open your browser to <a href="http://localhost:3000/fetch-image?f=sample.jpg">http://localhost:3000/fetch-image?f=sample.jpg</a></p><p>An error message should be present in the screen. This is because you probably don’t have reading access to your S3 bucket at the moment.</p><p><strong>Create an AWS user<br></strong>You’ll need to create a new IAM user in AWS, and configure your local machine to use those credentials for accessing your S3 bucket.</p><p>First of all create a new credential from your AWS IAM dashboard on <a href="https://console.aws.amazon.com/iam/home">https://console.aws.amazon.com/iam</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*e8sdhZL-sgKsTxY7j5VcnA.png" /><figcaption>Click Users, then Create a new user</figcaption></figure><p>Create a new user called serverless-image-rendering and make sure the Programmatic access option is selected — this will be required for Lambda in later steps.</p><p>Create and name a New Group, and check the “AdministratorAccess” from the policies listed. Now all you have to do is create a credentials file under your ~/.aws folder, and paste your IAM informations inside using the following format:</p><pre>[serverless-image-rendering]<br>aws_access_key_id=YOUR_USER_ACCESS_KEY<br>aws_secret_access_key=YOUR_USER_SECRET</pre><p>You can set your local preferences to use that profile using your terminal with the following command:</p><pre>export AWS_PROFILE=serverless-image-rendering</pre><p>Now you should be able to tart your NodeJS app, and open your browser to <a href="http://localhost:3000/fetch-image?f=sample.jpg">http://localhost:3000/fetch-image?f=sample.jpg</a>, and you’ll be able to see your S3 image appearing on your screen!</p><h4>Create the function for image processing</h4><p>The core piece for our app is the image processor responsible for dynamically scaling and changing the quality of your source image.</p><p>For serving this purpose, I’m going to use <a href="http://sharp.dimens.io/en/stable/">Sharp</a>. The implementation is really straight forward — this is the class I created inside a new src/image-resizer.js file</p><pre>class ImageResizer {<br>  constructor(Sharp) {<br>    this.sharp = Sharp;<br>  }<br>  <br>  resize(image, size, quality) {<br>    if (!image) throw new Error(&#39;An Image must be specified&#39;);<br>    if (!size) throw new Error(&#39;Image size must be specified&#39;);</pre><pre>    return new Promise((res, rej) =&gt; {<br>      this.sharp(new Buffer(image.buffer))<br>        .resize(size.w, size.h)<br>        .webp({quality: quality})<br>        .toBuffer()<br>        .then(data =&gt; {<br>          return res({<br>            image: data,<br>            contentType: &#39;image/webp&#39;,<br>          });<br>        })<br>        .catch(err =&gt; rej(err))<br>    });<br>  }<br>}</pre><pre>module.exports = ImageResizer;</pre><p>The resize method is going to receive an image buffer, a size object containing the width and height value for the new image, and a quality attribute.</p><p>First, let’s install Sharp in our project.</p><pre>$ npm i -S sharp</pre><p>Next, let’s create a new resize-image endpoint inside our Express app to consume ImageResizer.</p><pre>// app.js<br>const Sharp = require(&#39;sharp&#39;);<br>const ImageResizr = require(&#39;./src/image-resizer&#39;);<br>...<br>app.get(&#39;/resize-image&#39;, (req, res) =&gt; {<br>  const imageFetcher = new ImageFetcher(process.env.BUCKET);<br>  const imageResizr = new ImageResizer(Sharp);<br>  const fileName = req.query &amp;&amp; req.query.f;<br>  const quality = req.query &amp;&amp; +req.query.q || 80;<br>  const size = {<br>    w: req &amp;&amp; +req.query.w || 800,<br>    h: req &amp;&amp; +req.query.h || null,<br>  };</pre><pre>  return imageFetcher<br>    .fetchImage(fileName)<br>    .then(data =&gt; imageResizr.resize(data.image, size, quality))<br>    .then(data =&gt; {<br>      const img = new Buffer(data.image.buffer, &#39;base64&#39;);<br>      res.writeHead(200, {<br>        &#39;Content-Type&#39;: data.contentType<br>      });<br>      res.end(img);<br>    })<br>    .catch(error =&gt; {<br>      console.error(&#39;Error:&#39;, error);<br>      res.status(400).send(error.message || error);<br>    });<br>});</pre><p>Cool! Let’s give it a go.</p><p>Bootstrap your Node app once again, and this time open your browser to <a href="http://localhost:3000/resize-image?f=sample.jpg">http://localhost:3000/resize-image?f=sample.jpg</a></p><p>By default the image size is going to be 800px and the quality to 80%. However, we can now change size and quality by simply passing a query string to the URL. We can specify an image width passing the w key, height with the h key, and set a custom quality using the q key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Jq189nez6hNatVOxpPsQ6g.jpeg" /><figcaption><a href="http://localhost:3000/resize-image?f=sample.jpg&amp;w=600&amp;q=10">http://localhost:3000/resize-image?f=sample.jpg&amp;w=600&amp;q=10</a></figcaption></figure><p>We can now display our image resized to 600px pixels with a quality of 10% by just pasting our preferred values as parameters in the address bar.</p><h4>Now let’s go serverless</h4><p>So far, we just created a normal NodeJS app — so nothing is working serverless yet. Is this just a typo in the article name? Of course not!</p><p>Adding serverless is something you can easily do on top of your conventional NodeJS app. All we need is a serverless configuration file called serverless.yml that we’re going to create inside our project’s root directory.</p><p>For this specific project we’re also going to install two serverless plug-ins called serverless-apigw-binary and serverless-apigy-binary. The serverless framework will automatically configure the AWS API gateway to serve the response in application/json format, but we need to deliver an image — so we’ll need to rewrite the document ContentType to be image/webp instead.</p><p>Let’s start with installing all the Node modules we require for this final step</p><pre>$ npm i -S serverless-apigw-binary serverless-apigwy-binary</pre><p>Now open your new serverless.yml file and paste the following configuration inside:</p><pre>service: serverless-image-rendering<br>custom:<br>  apigwBinary:<br>  types:<br>    - &#39;*/*&#39;<br>provider:<br>  name: aws<br>  runtime: nodejs6.10<br>  stage: dev<br>  region: us-east-1<br>  timeout: 5 # optional, in seconds, default is 6<br>  role: ImageRenderingRole</pre><pre>environment:<br>  BUCKET: images-bucket<br>plugins:<br>  - serverless-apigw-binary<br>  - serverless-apigwy-binary</pre><pre>functions:<br>  resizeImage:<br>  handler: handler.resizeImage<br>  events:<br>    - http:<br>      path: resize-image<br>      method: get<br>      contentHandling: CONVERT_TO_BINARY</pre><pre>resources:<br>  Resources:<br>    ImageRenderingRole:<br>      Type: AWS::IAM::Role<br>      Properties:<br>        RoleName: ${self:service}-S3-ACCESS<br>        AssumeRolePolicyDocument:<br>        Version: &quot;2012-10-17&quot;<br>        Statement:<br>          - Effect: Allow<br>            Principal:<br>              Service:<br>                - lambda.amazonaws.com<br>            Action: sts:AssumeRole<br>      Policies:<br>        - PolicyName: ${self:service}-s3-access<br>          PolicyDocument:<br>            Version: &quot;2012-10-17&quot;<br>            Statement:<br>              - Effect: Allow<br>                Action:<br>                  - &quot;s3:GetObject&quot;<br>                Resource:<br>                  - &#39;arn:aws:s3:::${self:provider.environment.BUCKET}/*&#39;</pre><p>This configuration is going to create a Lambda function called “resizeImage”, which invokes a resizeImage function located inside a handler.js file</p><pre>functions:<br> resizeImage:<br> handler: handler.resizeImage</pre><p>It will also configure your API Gateway to invoke that function on any GET request to a resize-image path and return the response in binary format.</p><pre>events:<br>    - http:<br>      path: resize-image<br>      method: get<br>      contentHandling: CONVERT_TO_BINARY</pre><p>Serverless will also create a new AWS IAM Role for you called “serverless-image-rendering-S3-ACCESS” for allowing the Lambda function to read from your S3 Bucket.</p><p>While you can also create all of this manually from your AWS dashboard, the serverless framework will save you a lot of time and manual configuration.</p><h4>From Express to Lambda</h4><p>In the previous step, I mentioned a handler.js file — but we now have an app.js file instead. This is because we cannot run our Express app on Lambda, so we need to create a new file to upload to AWS. It will be similar to our previous app.js but without Express.</p><p>So, let’s create a new handler.js file in your project’s root folder. We can just paste inside the previous resize-image logic, and convert it into Lambda code like this:</p><pre>const Sharp = require(&#39;sharp&#39;);<br>const ImageFetcher = require(&#39;./src/s3-image-fetcher&#39;);<br>const ImageResizer = require(&#39;./src/image-resizer&#39;);</pre><pre>module.exports.resizeImage = (event, context, callback) =&gt; {<br>  const imageFetcher = new ImageFetcher(process.env.BUCKET);<br>  const imageResizer = new ImageResizer(Sharp);<br>  const fileName = event.queryStringParameters &amp;&amp; event.queryStringParameters.f;<br>  const quality = event.queryStringParameters &amp;&amp; +event.queryStringParameters.q || 80;<br>  const size = {<br>    w: event &amp;&amp; +event.queryStringParameters.w || 800,<br>    h: event &amp;&amp; +event.queryStringParameters.h || null,<br>  };</pre><pre>  return imageFetcher.fetchImage(fileName)<br>    .then(data =&gt; <br>      imageResizer.resize(data.image, size, quality))<br>    .then(data =&gt; {<br>      const contentType = data.contentType;<br>      const img = new Buffer(data.image.buffer, &#39;base64&#39;);</pre><pre>      callback(null, {<br>        statusCode: 200,<br>        headers: { &#39;Content-Type&#39;: contentType },<br>        body: img.toString(&#39;base64&#39;),<br>        isBase64Encoded: true,<br>      });<br>    })<br>    .catch(error =&gt; {<br>      console.error(&#39;Error:&#39;, error);<br>      callback(null, error);<br>    });<br>};</pre><p>This is pretty much the same code we wrote before — but we need to specify this “isBase64Encoded” for Lambda to be able to read our image correctly.</p><h4>Deploying code using Serverless CLI</h4><p>Ok, we’re now ready to deploy our code live! The first step requires you to install Serverless globally on your machine with the following command:</p><pre>$ npm i -g serverless</pre><p>Now, we can easily deploy all the code we’ve created:</p><pre>$ serverless deploy</pre><p>This operation will take a couple of minutes. Serverless is going to package your local application containing all the node dependencies inside a zip file, and upload it inside a new S3 container. Then it’s going to create a new IAM credential, an API Gateway and a Lambda function.</p><p>When the deployment process is finished, you’ll see your new Lambda endpoint in your terminal. You can also retrieve your AWS information at any time with the following command:</p><pre>$ serverless info</pre><p>And you’ll see something like this in response:</p><pre>Service Information<br>service: serverless-image-rendering<br>stage: dev<br>region: us-east-1<br>stack: serverless-image-rendering-dev<br>api keys:<br>  None<br>endpoints:<br>  GET - <a href="https://y7p8ti99y5.execute-api.us-east-1.amazonaws.com/dev/resize-image">https://xxx.us-east-1.amazonaws.com/dev/resize-image</a><br>functions:<br>  resizeImage: serverless-image-rendering-dev-resizeImage</pre><p>Now you should be able to copy the GET endpoint and paste it inside your browser. You’ll be able to see your new serverless app work by passing the same parameters used earlier within your local app and environment.</p><pre>For example:<br><a href="https://y7p8ti99y5.execute-api.us-east-1.amazonaws.com/dev/resize-image">https://xxx.us-east-1.amazonaws.com/dev/resize-image</a>?f=sample.jpg&amp;w=600&amp;q=10</pre><p><strong>Node modules issues<br></strong>You might encounter a problem when deploying to Lambda function. The problem is that your node modules are installed for a wrong environment configuration compared to AWS — so some packages like Sharp may not work inside your Lambda function. For this reaso, AWS released a Docker image called <a href="https://github.com/lambci/docker-lambda">lambci/lambda</a> that you can use for installing all the node modules before running serverless deploy</p><h4>Thanks for reading</h4><p>I created a <a href="https://github.com/andreasonny83/serverless-image-rendering">GitHub repository</a> where you can see the code related to this article — feel free to clone and create your own image processing app using a Lambda function. I’m looking forward to your feedback and comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=510b6c311fe5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/a-cloud-guru/serverless-image-optimization-and-delivery-510b6c311fe5">How to build a serverless app for on-demand image processing</a> was originally published in <a href="https://medium.com/a-cloud-guru">A Cloud Guru</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Component library: The Definitive Guide]]></title>
            <link>https://medium.com/@andreasonny83/angular-component-library-the-definitive-guide-91b43ac5e3af?source=rss-38c2afea51f------2</link>
            <guid isPermaLink="false">https://medium.com/p/91b43ac5e3af</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular-library]]></category>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[angular-component-library]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Andrea Sonny]]></dc:creator>
            <pubDate>Sat, 16 Dec 2017 23:33:27 GMT</pubDate>
            <atom:updated>2018-06-12T18:42:57.688Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P2pOvdhnhibwodvK." /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There’s plenty of articles around the web about creating Angular components and libraries so what’s the point in creating another one?<br>Well, after having followed almost any publicly available source of information about this topic around the web, I came to the conclusion that they are all uncompleted and superficials so I’ve never been able to create my production-ready library following their article. Then I decided to create this post, hoping to help future developer struggling with the same problematics I encountered.</p><p>Angular CLI is for sure one of the best tools available for building Angular applications. It’s a powerful tool when it comes to creating applications but is not really helpful when you need to create a reusable module or even worse a component library.</p><p>Good news! The CLI team is aware of this and is already working on an official solution for developing component library using Angular CLI. In the meantime, however, we need a plan-B.</p><p>My solution requires a combination of 2 independent Angular CLI projects and a lib folder containing my distribution-ready component library.</p><h3>Project structure</h3><p>What we need in our project, as already mentioned before, is 1 Angular-CLI project for developing our library, 1 folder containing the library itself and 1 extra Angular CLI project for 2 reasons: Creating a documentation app and testing our library inside an external application for simulating a real implementation of our library. <br>Our goal is in fact to release a library ready to be installed inside any Angular application so, the only way we have for making sure our library is serving that nrwl.io is installing it inside an external Angular application and making sure is working with both JiT and AoT compilation.</p><p>The following screenshot represent my ideal library project structure.<br>The root folder is where I bootstrapped my development Angular-CLI application and my library is living inside the source folder of it.<br>There is a second Angular-CLI application installed inside the doc folder but we can ignore that for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*tT47nR8IhutOATEaNFwawQ.png" /></figure><h3>Why should I care about AoT?</h3><p>From <a href="https://angular.io/guide/aot-compiler">https://angular.io/guide/aot-compiler</a></p><blockquote><em>Faster rendering<br></em>With AOT, the browser downloads a pre-compiled version of the application. The browser loads executable code so it can render the application immediately, without waiting to compile the app first.</blockquote><blockquote><em>Fewer asynchronous requests<br></em>The compiler <em>inlines</em> external HTML templates and CSS style sheets within the application JavaScript, eliminating separate ajax requests for those source files.</blockquote><blockquote><em>Smaller Angular framework download size<br></em>There’s no need to download the Angular compiler if the app is already compiled. The compiler is roughly half of Angular itself, so omitting it dramatically reduces the application payload.</blockquote><blockquote><em>Detect template errors earlier<br></em>The AOT compiler detects and reports template binding errors during the build step before users can see them.</blockquote><blockquote><em>Better security<br></em>AOT compiles HTML templates and components into JavaScript files long before they are served to the client. With no templates to read and no risky client-side HTML or JavaScript evaluation, there are fewer opportunities for injection attacks.</blockquote><h3>Before we start</h3><p>Because we need to make sure our library is both AoT and JiT ready, there are a couple of thinks that needs to be clarified before writing any code. There is a good article from <a href="https://medium.com/u/111a108c5d58">Isaac Mann</a> available <a href="https://blog.angularindepth.com/making-your-angular-2-library-statically-analyzable-for-aot-e1c6f3ebedd5">here</a> . Highly recommend a good read.</p><p>This is what I believe are the most important points to remember:</p><h4>Any member accessed from the template must be public</h4><pre>@Component({<br>  template: `&lt;div&gt; {{ context }} &lt;/div&gt;`<br>})<br>export class SomeComponent {<br>  private context: any;<br>}</pre><p>This will work with Just-in-Time compilation but will break AoT.<br>The private context variable needs to be changed public instead of private.</p><h4>Export components explicitly</h4><h4>Error:</h4><blockquote>Uncaught Error: Unexpected value ‘undefined’ imported by the module ‘AppModule’</blockquote><h4>Before:</h4><p>export * from &#39;some-component&#39;;</p><h4>After:</h4><p>export { SomeComponent } from &#39;some-component&#39;;</p><h4>peerDependency</h4><p>This is another good point as I noticed some open-source libraries don’t include any peerDependencies in their package.json. This can lead to several problems when the library is installed in a project with different package versions.</p><p>Have a look at <a href="https://nodejs.org/en/blog/npm/peer-dependencies/">this NodeJS article</a> for more information.</p><h3>Starting from scratch</h3><p>Create a new Angular-CLI project with ng new angular-component-library assuming that you’ve already installed Angular CLI globally on your machine (If not, <a href="https://cli.angular.io/">follow the official documentation</a>).</p><p>Now, we have our Development app that will be used for developing and testing our component library.</p><h3>Writing our library</h3><p>First of all, we’re not going to create an Angular module but a library which is a collection of modules. This means that we’re going to have several independent modules sitting together inside the same box and ready to be used inside any Angular application.</p><p>This means that our lib folder will just export all the different public folders for our library and containing one or more modules each.</p><p>Our lib file structure will be then something similar to this:</p><pre>.<br>├── lib<br>|   ├── module-a<br>|   |   ├── components<br>|   |   |   ├── component-a<br>|   |   |   |   ├── component-a.component.html<br>|   |   |   |   ├── component-a.component.css<br>|   |   |   |   ├── component-a.component.ts<br>|   |   |   |   ├── component-a.component.spec.ts<br>|   |   |   |   └── index.ts<br>|   |   |   └── index.ts<br>|   |   ├── module-a.module.ts<br>|   |   └── index.ts<br>|   ├── module-b<br>|   |   └── ...<br>|   └── index.ts</pre><p>The index.ts file sitting inside the root directory of lib will be responsible for exporting all the public modules in our project and will be something similar to this:</p><pre>export * from &#39;./module-a/index&#39;;<br>export * from &#39;./module-b/index&#39;;<br>export * from &#39;./module-c/index&#39;;<br>export * from &#39;./shared/index&#39;;</pre><p>Then, the main index.ts files sitting inside each module folders will export all the different elements of the module itself:</p><pre>// lib/module-a/index.ts<br>export { ComponentAService } from &#39;./services/index&#39;;<br>export { ComponentAComponent } from &#39;./components/index&#39;;<br>export { ComponentAModule } from &#39;./component-a.module&#39;;</pre><p>Noticed all those /index ? Well, it turns out that we need to specify them when we want to keep advantage of barrels where using export keyword. If missing, the type definition will be compromised during the library packaging process using the Typescript compiler (AKA tsc). There are several discussions and issues reported about this topic around the web and it took me a long while to figure it out.</p><p>I can share this issue reported on the Typescript repository as an example: <a href="https://github.com/Microsoft/TypeScript/issues/12974">https://github.com/Microsoft/TypeScript/issues/12974</a></p><h3>Library development</h3><p>Now we can start writing our components library and see them in action using the Angular-CLI development project so we can benefit from the scaffolding tool for generating our modules, components, etc and having a live reload listening to both the development app and our library which is sitting inside.</p><h3>Module Resolution</h3><p>It would be great if we can refer, from inside our development application, to our library like it was a real package sitting inside our node_module folder. So let’s do that!</p><p>From the Typescript documentation:</p><blockquote>The TypeScript compiler supports the declaration of such mappings using &quot;paths&quot; property in tsconfig.json files. Here is an example for how to specify the &quot;paths&quot; property for jquery.</blockquote><pre>{<br>  &quot;compilerOptions&quot;: {     <br>    &quot;baseUrl&quot;: &quot;.&quot;, // This must be specified if &quot;paths&quot; is.<br>    &quot;paths&quot;: {<br>      &quot;jquery&quot;: [&quot;node_modules/jquery/dist/jquery&quot;] // This mapping is relative to &quot;baseUrl&quot;<br>    }<br>  }<br>}</pre><p>For more information, refer to the official documentation available at: <a href="https://www.typescriptlang.org/docs/handbook/module-resolution.html">https://www.typescriptlang.org/docs/handbook/module-resolution.html</a></p><p>Using the typescript configuration file, we can create a map to our library to be used inside our development app without the need of specifying its relative path.</p><p>So, let’s edit the tsconfig.app.json file located inside the src folder of our application, and add the following “paths” node:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    ...<br>    &quot;paths&quot;: {<br>      &quot;@my/lib&quot;: [&quot;lib/public_api.ts&quot;]<br>    }<br>  }<br>}</pre><p>Note that we don’t need to include the same paths inside the tsconfig.spec.ts as we’re not going to have unit test inside the development application, instead, all the spec files will be only sitting inside the lib folder.</p><p>Now we can simply refer to @my/lib inside our development application like the following example:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br>import { RoutingModule } from &#39;./accordion.routing&#39;;<br>import { AccordionPageComponent } from &#39;./accordion.component&#39;;<br>import { AccordionModule } from &#39;@my/lib&#39;; // &#39;@my/lib&#39; can be replaced with &#39;../../../lib&#39;</pre><pre>@NgModule({<br>  declarations: [AccordionPageComponent],</pre><pre>imports: [<br>  CommonModule,<br>  AccordionModule,<br>  RoutingModule<br>]<br>})<br>export class PageModule { }</pre><h3>Packaging</h3><p>For packaging my library, I’m going to use <a href="https://github.com/dherges/ng-packagr">ng-packgr</a>. This is a great tool for generating production-ready Angular library with zero (or very close to) configuration. Ng-packgr follows the <a href="https://docs.google.com/document/d/1CZC2rcpxffTDfRDs6p1cfbmKNLA6x5O-NtkJglDaBVs/preview">Angular Package Format</a> guideline and the best practices suggested by <a href="https://github.com/jasonaden">Jason Aden</a> (Library developer at Google). <a href="https://youtu.be/unICbsPGFIA">Watch this great video from NG-Cong 2017 about Packaging Angular</a>.</p><p>ng-packgr needs 1 configuration file and 1 npm dependency.</p><pre>npm i -D ng-packagr</pre><p>Then update your package.json file with a package script:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;package&quot;: &quot;ng-packagr -p src/lib/ng-package.json&quot;<br>  }<br>}</pre><p>The configuration is picked up from the cli -p parameter, then from the ng-package.json.</p><p>Inside the src/lib/ng-package.json we need to write the following configuration:</p><pre>{<br>  &quot;$schema&quot;: &quot;../../node_modules/ng-packagr/ng-package.schema.json&quot;,<br>  &quot;dest&quot;: &quot;../../package&quot;,<br>  &quot;lib&quot;: {<br>    &quot;entryFile&quot;: &quot;public_api.ts&quot;<br>  }<br>}</pre><p>The default entry-file is set to public_api.ts. We can either create a public_api.ts file inside our lib folder or set index.ts to be our new entry-file.</p><p>We also need a package.json for our library. We can theoretically recycle the one sitting inside our root folder but is full of unnecessary packages because contains all the dependencies for our sandbox application. When we deliver an npm package we just want that to rely its own dependencies and not to carry over unwanted packages. Also, because we’re going to release an Angular library, we’ll need to specify some peer dependencies to avoid conflicts.</p><p>Then, the best way for having a clean package.json for our library is to create a brand new one inside our lib folder to be used for the distribution version of the library itself.</p><p>I created a very basic bash script in my root folder to dynamically replace some placeholders in a package.tpl.json file inside src/lib/ directory. In this way I can have the package name and version automatically synchronised with my main package.json file without the need of replacing the value twice every time I release a newer version of my library, then I created a prepackage script to be launched by npm to execute my script.</p><p><strong>package.json</strong></p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;prepackage&quot;: &quot;./predeploy.sh&quot;<br>  }<br>}</pre><p><strong>predeploy.sh</strong></p><pre>#!/bin/bash</pre><pre>PACKAGE_VERSION=$(grep -m1 version package.json | awk -F: &#39;{ print $2 }&#39; | sed &#39;s/[&quot;, ]//g&#39;)</pre><pre>PACKAGE_NAME=$(grep -m1 name package.json | awk -F: &#39;{ print $2 }&#39; | sed &#39;s/[&quot;, ]//g&#39;)</pre><pre>sed -e &quot;s/{version}/${PACKAGE_VERSION}/&quot; -e &quot;s#{pkg-name}#${PACKAGE_NAME}#&quot; src/lib/package.tpl.json &gt; src/lib/package.json</pre><p><strong>src/lib/package.tmp.json</strong></p><pre>{<br>  &quot;name&quot;: &quot;{pkg-name}&quot;,<br>  &quot;version&quot;: &quot;{version}&quot;,<br>  &quot;peerDependencies&quot;: {<br>    &quot;@angular/core&quot;: &quot;^4.0.0 || ^5.0.0&quot;,<br>    &quot;@angular/common&quot;: &quot;^4.0.0 || ^5.0.0&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;@angular/cdk&quot;: &quot;^2.0.0-beta.12&quot;,<br>  }<br>}</pre><p>Now, running npm run package will generate a package folder containing your library’s package.json with the correct dependencies.</p><h3>Documentation time</h3><p>Now that our library is ready for “going live” we can talk about that doc folder I mentioned before.</p><p>I said that we’re going to use another Angular-CLI project for both testing our library in action and providing a library documentation.</p><p>Inside my doc folder I bootstrapped and Angular-CLI project and removed all the testing tools and logic, which means that I deleted the e2e folder and all the karma and protractor code related to the documentation application as our library has already been unit and e2e tested from inside the src folder. The purpose of this project is to provide a documentation to our library so it doesn’t need to be tested but it will act as acceptance test for our library to make sure the final users will be able to consume our creation inside their projects.</p><p>For doing this, there are 2 possible ways (actually 3 because you can also create a symlink of the package but that can lead to other unwanted side-effects so I’m not going to talk about that in this article).</p><ul><li>Deploying the generated library to an npm repository and installing it inside our doc application.</li><li>The second, and the one I prefer, is to package the generated distribution version of the library and install that locally inside the doc application using npm.</li></ul><p>We can use npm pack inside our generated distribution version of the package, for generating a tarball file ready to be installed with npm like a normal npm package using npm install .</p><p>I defined a doc script inside my package.json to automate that process and serve the doc application with my latest version of the library injected inside.</p><pre>&quot;scripts&quot;: {<br>  &quot;doc:clean&quot;: &quot;rimraf doc/package-lock.json doc/node_modules&quot;,<br>  &quot;prepack-lib&quot;: &quot;npm run package&quot;,<br>  &quot;pack-lib&quot;: &quot;cd package &amp;&amp; npm pack&quot;,<br>  &quot;predoc:serve&quot;: &quot;npm run pack-lib &amp;&amp; npm run doc:clean&quot;,<br>  &quot;doc:serve&quot;: &quot;cd doc &amp;&amp; npm i &amp;&amp; npm i ../package/*.tgz --no-save &amp;&amp; npm start&quot;<br>}</pre><p>What I’m doing here is generating a fresh new distribution-ready version of my library, packaging everything and installing the generated tgz file inside my doc app. Note that I specify --no-save , that is because I don’t want to update the doc’s package.json dependencies with my library as I want to manually install that every time I run the documentation project to make sure I’m always using the latest version of the generated library. <br>I’m also using <a href="https://github.com/isaacs/rimraf">rimraf</a> for cleaning all the node modules installed and the package-lock.json file that Node &gt;8 generates automatically. I’m using <a href="https://github.com/isaacs/rimraf">rimraf</a> installed as a devDependenciy inside my project instead of rm -rf because it automatically deletes all files and folders recursively and doesn’t complain if the target file doesn’t exist.</p><h3>Automated documentation</h3><p>As an extra, I’m using <a href="https://compodoc.github.io/website/">Compodoc</a> on top of my documentation app to automatically generates an API documentation for my library using the power of the type definition. A good documentation example using a combination of Angular and Compodoc is available <a href="https://mattlewis92.github.io/angular-gauge/">here</a>.</p><p>What I’m doing is installing Compodoc as a development dependency of my project and generegate the documentation project inside my doc folder.</p><pre>&quot;predoc:build&quot;: &quot;cd doc &amp;&amp; npm i &amp;&amp; npm i ../package/*.tgz --no-save &amp;&amp; npm build --prod&quot;,<br>&quot;doc:build&quot;: &quot;compodoc -p src/lib/tsconfig-compodoc.json -d doc/docs&quot;</pre><p>The tsconfig-compodoc.json is required for specifying the files you want to use for generating the documentation. <br>I’m also using a different tsconfig file as I don’t want to document my development application but only the library sitting inside.</p><h3>That’s all folks!</h3><p>I really hope this guide will guide you in your library development process and will answer all your questions about that process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91b43ac5e3af" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>