<?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[Code - Medium]]></title>
        <description><![CDATA[A journal of a passionate coder - Medium]]></description>
        <link>https://medium.com/risan?source=rss----b42a56310d1c---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Code - Medium</title>
            <link>https://medium.com/risan?source=rss----b42a56310d1c---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 04:12:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/risan" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Bundling Your JavaScript Library with Rollup]]></title>
            <link>https://medium.com/risan/bundling-your-javascript-library-with-rollup-73be9620be09?source=rss----b42a56310d1c---4</link>
            <guid isPermaLink="false">https://medium.com/p/73be9620be09</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[bundler]]></category>
            <category><![CDATA[rollup]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Risan Bagja]]></dc:creator>
            <pubDate>Sun, 12 Sep 2021 14:06:55 GMT</pubDate>
            <atom:updated>2021-09-12T14:13:55.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GY8qPeBy2D52yZop.png" /></figure><p>Similar to Webpack or Browserify, <a href="https://rollupjs.org/">Rollup</a> is a module bundler for JavaScript. It allows us to use the modern ES module system and transform it into another module system: CommonJS, AMD, or UMD. It can also bundle our module and wrap it inside the IIFE (Immediately-Invoked Function Expression).</p><p>Though people usually use Rollup to bundle a library. It’s possible to bundle an application too.</p><blockquote><em>You can access the source code for this tutorial here: </em><a href="https://github.com/risan/eat-fruit"><em>github.com/risan/eat-fruit</em></a><em>.</em></blockquote><h3>Installation</h3><p>To install Rollup globally, run the following command on your terminal:</p><pre>$ npm install -g rollup</pre><pre># Or if you prefer to use Yarn<br>$ yarn global add rollup</pre><p>You can now run the following command to print the Rollup CLI help:</p><pre>$ rollup -h</pre><h3>Quick Start</h3><p>To see Rollup in action, let’s create a simple ES module:</p><pre>// main.js<br>const eat = food =&gt; console.log(`I eat ${food}.`);</pre><pre>export default eat;</pre><p>It is just a simple function that will print I eat something on the console or the terminal. Save the file as main.js. On the terminal type the following command to transform our ES module into a CommonJS module:</p><pre>$ rollup main.js --file bundle.js --format cjs</pre><ul><li>--file: The path for the output file</li><li>--format: The targetted output format, in our case the cjs is for the CommonJS module.</li></ul><p>Along with the main.js file, we should now have the bundle.js file. If we open the bundle.js file, we&#39;ll see that our eat function is now using the CommonJS module.</p><pre>// bundle.js<br>&#39;use strict&#39;;</pre><pre>const eat = food =&gt; console.log(`I eat ${food}.`);</pre><pre>module.exports = eat;</pre><p>If you’re familiar with Node.js, that’s how you usually export a module.</p><h3>Exploring Other Output Formats</h3><p>Rollup offers five output formats for your bundle:</p><ul><li>cjs: The CommonJS module that typically targeted for the Node.js environment.</li><li>amd: The AMD module which usually used in the browser.</li><li>umd: The UMD module which often use to target both the Node.js and the browser environments.</li><li>es: The ES module itself.</li><li>iife: Which will wrap our bundle within the IIFE (Immediately-Invoked Function Expression) for browser usage.</li></ul><h4>AMD Output</h4><p>Let’s bundle our main.js module into an AMD module:</p><pre>$ rollup main.js --file amd.js --format amd</pre><p>Here’s the generated amd.js file looks like:</p><pre>// amd.js<br>define(<em>function</em> () { &#39;use strict&#39;;</pre><pre>    const eat = food =&gt; console.log(`I eat ${food}.`);</pre><pre>    return eat;</pre><pre>});</pre><p>If you ever worked with <a href="https://requirejs.org/">RequireJS</a> or <a href="https://github.com/cujojs/curl">curl.js</a> in the past. You might notice the define function above. It&#39;s how you register a factory function in the AMD format.</p><h4>UMD Output</h4><p>Now, let’s create the UMD version:</p><pre>$ rollup main.js --file umd.js --format umd --name eat</pre><p>For UMD format, we also need to pass the --name option. It&#39;s the identifier that will be used to expose our module. We use the same name as our eat function. We can use a different name though.</p><p>If we open up the umd.js file, the generated code will look like this:</p><pre>(<em>function</em> (global, factory) {<br>    typeof exports === &#39;object&#39; &amp;&amp; typeof module !== &#39;undefined&#39; ? module.exports = factory() :<br>    typeof define === &#39;function&#39; &amp;&amp; define.amd ? define(factory) :<br>    (global.eat = factory());<br>}(this, (<em>function</em> () { &#39;use strict&#39;;</pre><pre>    const eat = food =&gt; console.log(`I eat ${food}.`);</pre><pre>    return eat;</pre><pre>})));</pre><p>It slightly looks more complicated than the previous output formats. It’s an IIFE that will check if the current environment supports a CommonJS or an AMD module format. If the current environment supports a CommonJS module, it will export our eat function.</p><pre>typeof exports === &#39;object&#39; &amp;&amp; typeof module !== &#39;undefined&#39; ? module.exports = factory()</pre><p>Or if the current environment supports an AMD module, it will register a factory function for our eat module.</p><pre>typeof define === &#39;function&#39; &amp;&amp; define.amd ? define(factory)</pre><p>Otherwise, it will add the eat function into the current this object:</p><pre>global.eat = factory()</pre><p>For example, if we load our umd.js file in the browser, we can access our eat function from the window object:</p><pre><em>window</em>.eat(&#39;🍕&#39;);</pre><h4>ES Output</h4><p>Rollup can also output the same exact ES module:</p><pre>rollup main.js --file es.js --format es</pre><p>If we check the generated es.js file, we&#39;ll find the identical code:</p><pre>const eat = food =&gt; console.log(`I eat ${food}.`);</pre><pre>export default eat;</pre><p>We use this option in case the users of our library want to use a tool that can leverage the ES module, like Webpack 2+.</p><h4>IIFE</h4><p>The last format that we can generate with Rollup is IIFE (Immediately-Invoked Function Expression):</p><pre>rollup main.js --file iife.js --format iife --name eat</pre><p>Just like the UMD format, we have to set the --name option. If we check the iife.js file, the eat function is wrapped within the IIFE block:</p><pre><em>var</em> eat = (<em>function</em> () {<br>    &#39;use strict&#39;;</pre><pre>    const eat = food =&gt; console.log(`I eat ${food}.`);</pre><pre>    return eat;</pre><pre>}());</pre><h3>Rollup Configuration File</h3><p>We can also use a configuration file to configure Rollup. Before continuing, let’s delete the generated files. Then move the main.js file into the src directory.</p><pre># Delete generated files<br>$ rm bundle.js amd.js umd.js es.js iife.js</pre><pre># Move main.js to src directory<br>$ mkdir src<br>$ mv main.js src</pre><p>Create a new file named rollup.config.js and put the following configuration object:</p><pre>// rollup.config.js<br>export default {<br>  input: &#39;src/main.js&#39;,<br>  output: {<br>    file: &#39;dist/cjs.js&#39;,<br>    format: &#39;cjs&#39;<br>  }<br>};</pre><p>Your current directory should now look like this:</p><pre>|-- rollup.config.js<br>|-- src<br>|   |-- main.js</pre><p>Run the following command to bundle our main.js file:</p><pre>$ rollup -c</pre><ul><li>-c: The config file path. If not set, it will look for the rollup.config.js file.</li></ul><p>We should now have the generated CommonJS file stored at: dist/cjs.js.</p><h4>Multiple Output Formats</h4><p>We can also assign an array to the output option to generate various output formats:</p><pre>// rollup.config.js<br>export default {<br>  input: &#39;src/main.js&#39;,<br>  output: [<br>    {<br>      file: &#39;dist/cjs.js&#39;,<br>      format: &#39;cjs&#39;<br>    },<br>    {<br>      file: &#39;dist/umd.js&#39;,<br>      format: &#39;umd&#39;,<br>      name: &#39;eat&#39;<br>    }<br>  ]<br>};</pre><p>If you run the rollup -c command again, it will generate two bundles with different module format: cjs and umd.</p><h4>Multiple Inputs</h4><p>It’s also possible to build bundles from multiple inputs:</p><pre>// rollup.config.js<br>export default [<br>  {<br>    input: &#39;src/main.js&#39;,<br>    output: [<br>      {<br>        file: &#39;dist/cjs.js&#39;,<br>        format: &#39;cjs&#39;<br>      },<br>      {<br>        file: &#39;dist/umd.js&#39;,<br>        format: &#39;umd&#39;,<br>        name: &#39;eat&#39;<br>      }<br>    ]<br>  },<br>  {<br>    input: &#39;src/other.js&#39;,<br>    output: {<br>      file: &#39;dist/other.bundle.js&#39;,<br>      format: &#39;cjs&#39;<br>    }<br>  }<br>];</pre><h3>Tree-Shaking</h3><p>One of the most amazing features on Rollup is its tree-shaking ability. RollUp can statically analyze our code and remove unused functions or modules from our bundle.</p><h4>Preparing Our Food Factory</h4><p>Within the src directory create a new file named food.js:</p><pre>// src/food.js<br>const FRUITS = [&#39;🍏&#39;, &#39;🍉&#39;, &#39;🍇&#39;];</pre><pre>const FAST_FOODS = [&#39;🍔&#39;, &#39;🍟&#39;, &#39;🍕&#39;];</pre><pre>const randomFruit = () =&gt;<br>  FRUITS[getRandomNumberBetween(0, FRUITS.length - 1)];</pre><pre>const randomFastFood = () =&gt;<br>  FAST_FOODS[getRandomNumberBetween(0, FRUITS.length - 1)];</pre><pre>const getRandomNumberBetween = (start, end) =&gt;<br>  <em>Math</em>.floor(<em>Math</em>.random() * end) + start;</pre><pre>export {<br>  FRUITS,<br>  FAST_FOODS,<br>  randomFruit,<br>  randomFastFood<br>};</pre><p>In this food module, we export two constants and two functions:</p><ul><li>FRUITS: An array of fruit emojis.</li><li>FAST_FOODS: An array of fast food emojis.</li><li>randomFruit: Function to get a random fruit emoji.</li><li>randomFastFood: Function to get a random fast food emoji.</li></ul><h4>Tree-Shaking in Action</h4><p>Let’s get back to our main.js file. Rename the eat function to eatFruit. Use the randomFruit function from our food module to generate a random fruit emoji:</p><pre>// src/main.js<br>import * as food from &#39;./food&#39;;</pre><pre>const eatFruit = () =&gt; console.log(`I eat ${food.randomFruit()}.`);</pre><pre>export default eatFruit;</pre><p>Type the following command on the terminal to bundle our main.js module into a CommonJS format.</p><pre>$ rollup src/main.js --file dist/bundle.js --format cjs</pre><p>Let’s inspect the generated bundle.js file:</p><pre>// dist/bundle.js<br>&#39;use strict&#39;;</pre><pre>const FRUITS = [&#39;🍏&#39;, &#39;🍉&#39;, &#39;🍇&#39;];</pre><pre>const randomFruit = () =&gt;<br>  FRUITS[getRandomNumberBetween(0, FRUITS.length - 1)];</pre><pre>const getRandomNumberBetween = (start, end) =&gt;<br>  <em>Math</em>.floor(<em>Math</em>.random() * end) + start;</pre><pre>const eatFruit = () =&gt; console.log(`I eat ${randomFruit()}.`);</pre><pre>module.exports = eatFruit;</pre><p>Even though we import the whole food module into our code, Rollup is smart enough to strip any unused parts. Both the FAST_FOODS constant and the randomFastFood function are excluded from the final bundle. Isn’t that awesome?</p><p>Even though Rollup is smart enough to exclude any unused functions or modules, it’s a good practice to explicitly export things that we only need. Let’s modify our main.js file to import the randomFruit function only:</p><pre>// src/main.js<br>import { randomFruit } from &#39;./food&#39;;</pre><pre>const eatFruit = () =&gt; console.log(`I eat ${randomFruit()}.`);</pre><pre>export default eatFruit;</pre><p>Run the command to bundle our main.js file again, we should have the same exact output.</p><pre>$ rollup src/main.js --file dist/bundle.js --format cjs</pre><h4>Three-Shaking Gotcha</h4><p>Suppose we use the default keyword to export the four items in the food.js module:</p><pre>// Omitted for brevity...</pre><pre>export default {<br>  FRUITS,<br>  FAST_FOODS,<br>  randomFruit,<br>  randomFastFood<br>};</pre><p>And the main.js file looks like this to accommodate that change:</p><pre>// src/main.js<br>import food from &#39;./food&#39;;</pre><pre>const eatFruit = () =&gt; console.log(`I eat ${food.randomFruit()}.`);</pre><pre>export default eatFruit;</pre><p>If we bundle that main.js file through Rollup, the output will look like this:</p><pre>// dist/bundle.js<br>&#39;use strict&#39;;</pre><pre>const FRUITS = [&#39;🍏&#39;, &#39;🍉&#39;, &#39;🍇&#39;];</pre><pre>const FAST_FOODS = [&#39;🍔&#39;, &#39;🍟&#39;, &#39;🍕&#39;];</pre><pre>const randomFruit = () =&gt;<br>  FRUITS[getRandomNumberBetween(0, FRUITS.length - 1)];</pre><pre>const randomFastFood = () =&gt;<br>  FAST_FOODS[getRandomNumberBetween(0, FRUITS.length - 1)];</pre><pre>const getRandomNumberBetween = (start, end) =&gt;<br>  <em>Math</em>.floor(<em>Math</em>.random() * end) + start;</pre><pre><em>var</em> food = {<br>  FRUITS,<br>  FAST_FOODS,<br>  randomFruit,<br>  randomFastFood<br>};</pre><pre>const eatFruit = () =&gt; console.log(`I eat ${food.randomFruit()}.`);</pre><pre>module.exports = eatFruit;</pre><p>Even though we’re not using them, we ended up having both FAST_FOODS and randomFastFood in our bundle file.</p><p>There’s another three-shaking gotcha explained in the next section that you should be aware of.</p><h4>Importing NPM Package</h4><p>We often need to pull a third-party library from NPM. For our example, let’s pull the lodash library. Within the project directory, type the following command to create an empty package.json file:</p><pre>$ <em>echo</em> {} &gt; package.json</pre><p>Then install the lodash-es package, it&#39;s the ES modules version for lodash:</p><pre>$ npm install lodash-es</pre><pre># Or if you prefer to use Yarn<br>$ yarn add lodash-es</pre><p>Open up the src/food.js file. Let’s replace the getRandomNumberBetween with the lodash’s random function instead.</p><pre>// src/food.js<br>import { random } from &#39;lodash-es&#39;;</pre><pre>const FRUITS = [&#39;🍏&#39;, &#39;🍉&#39;, &#39;🍇&#39;];</pre><pre>const FAST_FOODS = [&#39;🍔&#39;, &#39;🍟&#39;, &#39;🍕&#39;];</pre><pre>const randomFruit = () =&gt;<br>  FRUITS[random(0, FRUITS.length - 1)];</pre><pre>const randomFastFood = () =&gt;<br>  FAST_FOODS[random(0, FRUITS.length - 1)];</pre><pre>export {<br>  FRUITS,<br>  FAST_FOODS,<br>  randomFruit,<br>  randomFastFood<br>};</pre><p>This time we’re going to use the Rollup configuration file. On your project directory, create a new file named rollup.config.js:</p><pre>// rollup.config.js<br>export default {<br>  input: &#39;src/main.js&#39;,<br>  output: {<br>    file: &#39;dist/cjs.js&#39;,<br>    format: &#39;cjs&#39;<br>  }<br>};</pre><p>With this configuration file, we’re going to generate a bundle with CommonJS format. Let’s build our main.js file!</p><pre>$ rollup -c</pre><p>You’ll get a warning that it can’t resolve the lodash-es.</p><pre>(!) Unresolved dependencies<br>https://rollupjs.org/guide/en#warning-treating-module-as-external-dependency<br>lodash-es (imported by src/food.js)<br>created dist/cjs.js in 32ms</pre><p>If you check the generated dist/cjs.js file, you’ll see that the lodash code is not included. It is simply require the lodash-es module.</p><pre>&#39;use strict&#39;;</pre><pre><em>var</em> lodashEs = require(&#39;lodash-es&#39;);</pre><pre>const FRUITS = [&#39;🍏&#39;, &#39;🍉&#39;, &#39;🍇&#39;];</pre><pre>const randomFruit = () =&gt;<br>  FRUITS[lodashEs.random(0, FRUITS.length - 1)];</pre><pre>const eatFruit = () =&gt; console.log(`I eat ${randomFruit()}.`);</pre><pre>module.exports = eatFruit;</pre><p>The bundle will still work if the user of your library happens to have lodash-es installed on their project. Of course, it&#39;s not a reliable approach to build a library. So how can we solve this?</p><h4>Resolving Third-Party Modules with Plugin</h4><p>Luckily, there’s already a plugin to assist Rollup in resolving any third-party modules installed through NPM: <a href="https://github.com/rollup/rollup-plugin-node-resolve">rollup-plugin-node-resolve</a>. Let&#39;s install this plugin as our dev-dependency:</p><pre>$ npm install rollup-plugin-node-resolve -D</pre><pre># If you prefer to use Yarn<br>$ yarn add rollup-plugin-node-resolve -D</pre><p>Next, we need to register this plugin within our rollup.config.js file:</p><pre>// rollup.config.js<br>import resolve from &#39;rollup-plugin-node-resolve&#39;;</pre><pre>export default {<br>  input: &#39;src/main.js&#39;,<br>  output: {<br>    file: &#39;dist/cjs.js&#39;,<br>    format: &#39;cjs&#39;<br>  },<br>  plugins: [<br>    resolve()<br>  ]<br>};</pre><p>Let’s bundle our main.js file once again:</p><pre>$ rollup -c</pre><p>There’s no warning message this time! If you check the generated dist/cjs.js file, you should find the lodash code in the bundle.</p><p>But wait, why are there so many lodash codes in our bundle file? Though we only import the random function. 🤔</p><h4>Another Three-Shaking Gotcha</h4><p>Performing static analysis in a dynamic programming language like JavaScript is hard. Rollup has to be careful in removing any unused code to guarantee that the final bundle still works correctly.</p><p>If an imported module appears to have some side effects, Rollup needs to be conservative and includes those side-effects. Even though it may be a false positive, just like in our lodash case above.</p><p>In our lodash case, we can get around this by importing the submodule instead:</p><pre>// src/food.js<br>import random from &#39;lodash-es/random&#39;;</pre><pre>const FRUITS = [&#39;🍏&#39;, &#39;🍉&#39;, &#39;🍇&#39;];</pre><pre>const FAST_FOODS = [&#39;🍔&#39;, &#39;🍟&#39;, &#39;🍕&#39;];</pre><pre>const randomFruit = () =&gt;<br>  FRUITS[random(0, FRUITS.length - 1)];</pre><pre>const randomFastFood = () =&gt;<br>  FAST_FOODS[random(0, FRUITS.length - 1)];</pre><pre>export {<br>  FRUITS,<br>  FAST_FOODS,<br>  randomFruit,<br>  randomFastFood<br>};</pre><h4>Importing CommonJS Module</h4><p>The lodash-es package is using the ES module format. So Rollup can process it out of the box. Unfortunately, the majority of packages published on NPM are using the CommonJS format.</p><p>Let’s replace the lodash-es package with its CommonJS counterpart: lodash and see if Rollup can handle it.</p><pre>$ npm uninstall lodash-es<br>$ npm i lodash</pre><pre># If you use Yarn<br>$ yarn remove lodash-es<br>$ yarn add lodash</pre><p>Don’t forget to update the import statement on the food.js module:</p><pre>// src/food.js<br>import random from &#39;lodash/random&#39;;</pre><pre>const FRUITS = [&#39;🍏&#39;, &#39;🍉&#39;, &#39;🍇&#39;];</pre><pre>const FAST_FOODS = [&#39;🍔&#39;, &#39;🍟&#39;, &#39;🍕&#39;];</pre><pre>const randomFruit = () =&gt;<br>  FRUITS[random(0, FRUITS.length - 1)];</pre><pre>const randomFastFood = () =&gt;<br>  FAST_FOODS[random(0, FRUITS.length - 1)];</pre><pre>export {<br>  FRUITS,<br>  FAST_FOODS,<br>  randomFruit,<br>  randomFastFood<br>};</pre><p>Let’s run the Rollup command to bundle our main.js file:</p><pre>$ rollup -c</pre><p>We’ll end up having an error message like this:</p><pre>src/main.js → dist2/cjs.js...<br>[!] Error: &#39;default&#39; is not exported by node_modules/lodash/random.js<br>https://rollupjs.org/guide/en#error-name-is-not-exported-by-module-<br>src/food.js (1:7)<br>1: import random from &#39;lodash/random&#39;;</pre><p>It turns out Rollup can’t process the CommonJS format. Fortunately, there’s already a plugin to solve this issue: <a href="https://github.com/rollup/rollup-plugin-commonjs">rollup-plugin-commonjs</a>. This plugin will convert any CommonJS modules into the ES module format. That way Rollup can process them.</p><p>Let’s install this plugin:</p><pre>$ npm install rollup-plugin-commonjs -D</pre><pre># Or if you use yarn<br>$ yarn add rollup-plugin-commonjs -D</pre><p>Don’t forget to register it on rollup.config.js file:</p><pre>// rollup.config.js<br>import commonjs from &#39;rollup-plugin-commonjs&#39;;<br>import resolve from &#39;rollup-plugin-node-resolve&#39;;</pre><pre>export default {<br>  input: &#39;src/main.js&#39;,<br>  output: {<br>    file: &#39;dist/cjs.js&#39;,<br>    format: &#39;cjs&#39;<br>  },<br>  plugins: [<br>    resolve(),<br>    commonjs()<br>  ]<br>};</pre><p>Try to bundle our main.js file again. There should be no error this time.</p><pre>$ rollup - c</pre><blockquote><em>If you register other plugins that can also transform your module, make sure that the </em><em>rollup-plugin-commonjs comes before any of that plugins. It&#39;s to prevent the other plugins from making changes that may break the CommonJS detection.</em></blockquote><h4>Peer Dependencies</h4><p>Suppose that we decided to list lodash as our library’s peer dependencies. So instead of bundling lodash/random into our bundle, we’d ask the user to install lodash package separately.</p><p>We can achieve this by providing the external property to the rollup.config.js file:</p><pre>// rollup.config.js<br>import commonjs from &#39;rollup-plugin-commonjs&#39;;<br>import resolve from &#39;rollup-plugin-node-resolve&#39;;</pre><pre>export default {<br>  input: &#39;src/main.js&#39;,<br>  output: {<br>    file: &#39;dist/cjs.js&#39;,<br>    format: &#39;cjs&#39;<br>  },<br>  plugins: [<br>    resolve(),<br>    commonjs()<br>  ],<br>  external: [<br>    &#39;lodash/random&#39;<br>  ]<br>};</pre><p>The module listed on the external option must match exactly the same as how we imported it in our code. That’s why we use lodash/random instead of just lodash.</p><p>Let’s try to bundle our main.js file again:</p><pre>$ rollup -c</pre><p>If we peek at the generated dist/cjs.file, the lodash code is now excluded from our bundle:</p><pre>// dist/cjs.js<br>&#39;use strict&#39;;</pre><pre><em>function</em> _interopDefault (ex) { return (ex &amp;&amp; (typeof ex === &#39;object&#39;) &amp;&amp; &#39;default&#39; in ex) ? ex[&#39;default&#39;] : ex; }</pre><pre><em>var</em> random = _interopDefault(require(&#39;lodash/random&#39;));</pre><pre>const FRUITS = [&#39;🍏&#39;, &#39;🍉&#39;, &#39;🍇&#39;];</pre><pre>const randomFruit = () =&gt;<br>  FRUITS[random(0, FRUITS.length - 1)];</pre><pre>const eatFruit = () =&gt; console.log(`I eat ${randomFruit()}.`);</pre><pre>module.exports = eatFruit;</pre><p>If we choose to generate the umd or iife format, we have to specify the global option too. This option tells Rollup how to access that peer dependency.</p><pre>// rollup.config.js<br>import commonjs from &#39;rollup-plugin-commonjs&#39;;<br>import resolve from &#39;rollup-plugin-node-resolve&#39;;</pre><pre>export default {<br>  input: &#39;src/main.js&#39;,<br>  output: [<br>    {<br>      file: &#39;dist/cjs.js&#39;,<br>      format: &#39;cjs&#39;<br>    },<br>    {<br>      file: &#39;dist/umd.js&#39;,<br>      format: &#39;umd&#39;,<br>      name: &#39;eatFruit&#39;,<br>      globals: {<br>        &#39;lodash/random&#39;: &#39;_.random&#39;<br>      }<br>    },<br>    {<br>      file: &#39;dist/iife.js&#39;,<br>      format: &#39;iife&#39;,<br>      name: &#39;eatFruit&#39;,<br>      globals: {<br>        &#39;lodash/random&#39;: &#39;_.random&#39;<br>      }<br>    }<br>  ],<br>  plugins: [<br>    resolve(),<br>    commonjs()<br>  ],<br>  external: [<br>    &#39;lodash/random&#39;<br>  ]<br>};</pre><p>If we load lodash package in the browser, we can access it through the _ identifier.</p><blockquote><em>⚠️ </em><strong><em>WARNING</em></strong></blockquote><blockquote><em>If you list a package as a peer-dependency for your library, set the required version as loose as possible. At least don’t target the exact patch version. This is to avoid version incompatibility with other libraries.</em></blockquote><p>Before continuing to the next section, let’s revert our change by removing lodash/random module as the peer dependency. Simply remove the external option from rollup.config.js file:</p><pre>// rollup.config.js<br>import commonjs from &#39;rollup-plugin-commonjs&#39;;<br>import resolve from &#39;rollup-plugin-node-resolve&#39;;</pre><pre>export default {<br>  input: &#39;src/main.js&#39;,<br>  output: {<br>    file: &#39;dist/cjs.js&#39;,<br>    format: &#39;cjs&#39;<br>  },<br>  plugins: [<br>    resolve(),<br>    commonjs()<br>  ]<br>};</pre><h3>Compiling ES 2015+ Code with Babel</h3><p>You can use Babel with Rollup to transform your ES 2015+ code into a backward compatible version of JavaScript. This way your library can also be used in some older browsers or Node versions.</p><p>First, let’s install @babel/core, @babel/preset-env, and rollup-plugin-babel:</p><pre>$ npm install @babel/core @babel/preset-env rollup-plugin-babel -D</pre><pre># If you use Yarn<br>$ yarn add @babel/core @babel/preset-env rollup-plugin-babel -D</pre><p>With @babel/preset-env, we can easily target the minimum environments and don&#39;t need to choose Babel&#39;s plugins manually. The rollup-plugin-babel is the required plugin for Babel integration with Rollup.</p><p>Next, let’s create a .babelrc config file. Store it within the src directory instead of the project root directory. This way we can have different babel configurations for other parts, like tests.</p><pre>{<br>  &quot;presets&quot;: [<br>    [<br>      &quot;@babel/env&quot;,<br>      {<br>        &quot;modules&quot;: false,<br>        &quot;useBuiltIns&quot;: &quot;usage&quot;,<br>        &quot;targets&quot;: {<br>          &quot;node&quot;: &quot;4&quot;<br>        }<br>      }<br>    ]<br>  ]<br>}</pre><p>We set the modules to false to prevent Babel from transforming any ES modules. Rollup already handles this for us. We also set the useBuiltIns to usage to import polyfills for the features that we only use.</p><p>We also set the minimum Node version to 4. If we don&#39;t set the targets option, it will work exactly the same as using @babel/preset-es2015, @babel/preset-es2016, and @babel/preset-es2017 together.</p><blockquote><em>Node version 4 is already in the end-of-life. We targetted this version just to see the transformation made by Babel.</em></blockquote><p>Lastly, we need to register the rollup-plugin-babel plugin within the rollup.config.js file:</p><pre>import babel from &#39;rollup-plugin-babel&#39;;<br>import commonjs from &#39;rollup-plugin-commonjs&#39;;<br>import resolve from &#39;rollup-plugin-node-resolve&#39;;</pre><pre>export default {<br>  input: &#39;src/main.js&#39;,<br>  output: {<br>    file: &#39;dist/cjs.js&#39;,<br>    format: &#39;cjs&#39;<br>  },<br>  plugins: [<br>    resolve(),<br>    commonjs(),<br>    babel({<br>      exclude: &#39;node_modules/**&#39;<br>    })<br>  ]<br>};</pre><p>Note that we also pass the exclude option to exclude any codes from the node_modules directory from transformation. Let’s bundle our main.js file:</p><pre>$ rollup -c</pre><p>If you check the generated dist/cjs.js file, you&#39;ll find that our ES 2015 code is transformed into the ES5 standard:</p><pre>// Omitted for brevity...</pre><pre><em>var</em> FRUITS = [&#39;🍏&#39;, &#39;🍉&#39;, &#39;🍇&#39;];</pre><pre><em>var</em> randomFruit = <em>function</em> randomFruit() {<br>  return FRUITS[random_1(0, FRUITS.length - 1)];<br>};</pre><pre><em>var</em> eatFruit = <em>function</em> eatFruit() {<br>  return console.log(`I eat ${randomFruit()}.`);<br>};</pre><h4>Using Browserlist</h4><p>We can also use a <a href="https://github.com/browserslist/browserslist">browserslist</a> query for targetting the minimum environments. Let’s update our src/.babelrc file to target only Node versions that are still maintained:</p><pre>{<br>  &quot;presets&quot;: [<br>    [<br>      &quot;@babel/env&quot;,<br>      {<br>        &quot;modules&quot;: false,<br>        &quot;targets&quot;: &quot;maintained node versions&quot;<br>      }<br>    ]<br>  ]<br>}</pre><p>Check all of the possible browserslist queries here: <a href="https://github.com/browserslist/browserslist#full-list">Full List</a>.</p><p>Now run the Rollup command to bundle our main.js file:</p><pre>$ rollup -c</pre><p>If we check our code in the generated bundle file, it should now back to the ES 2015 syntax again:</p><pre>// Omitted for brevity...</pre><pre>const FRUITS = [&#39;🍏&#39;, &#39;🍉&#39;, &#39;🍇&#39;];</pre><pre>const randomFruit = () =&gt; FRUITS[random_1(0, FRUITS.length - 1)];</pre><pre>const eatFruit = () =&gt; console.log(`I eat ${randomFruit()}.`);</pre><p>It’s also possible for us to use the .browserslist configuration file. First, let’s remove the targets option from the src/.babelrc file:</p><pre>{<br>  &quot;presets&quot;: [<br>    [<br>      &quot;@babel/env&quot;,<br>      {<br>        &quot;modules&quot;: false<br>      }<br>    ]<br>  ]<br>}</pre><p>Next, create a new .browserslistrc file in the project root directory:</p><pre>maintained node versions</pre><p>We will get a similar output if we run the Rollup command again.</p><h4>Different Output Format, Different Minimum Environments</h4><p>Suppose that we want to generate a umd format. So it can be used in a browser too. Let&#39;s update our rollup.config.js file:</p><pre>// rollup.config.js<br>import babel from &#39;rollup-plugin-babel&#39;;<br>import commonjs from &#39;rollup-plugin-commonjs&#39;;<br>import resolve from &#39;rollup-plugin-node-resolve&#39;;</pre><pre>export default {<br>  input: &#39;src/main.js&#39;,<br>  output: [<br>    {<br>      file: &#39;dist/cjs.js&#39;,<br>      format: &#39;cjs&#39;<br>    },<br>    {<br>      file: &#39;dist/umd.js&#39;,<br>      format: &#39;umd&#39;,<br>      name: &#39;eatFruit&#39;<br>    }<br>  ],<br>  plugins: [<br>    resolve(),<br>    commonjs(),<br>    babel({<br>      exclude: &#39;node_modules/**&#39;<br>    })<br>  ]<br>};</pre><p>Let’s update our .browserslistrc file too:</p><pre>maintained node versions<br>last 1 version<br>&gt; 5%<br>not dead</pre><p>The above query means that we want to support:</p><ul><li>maintained node versions: All Node versions that are still maintained.</li><li>last 1 version: The last 1 version of each browser.</li><li>&gt; 5%: All browsers with more than 5% usage statistic.</li><li>not dead: And only include the browsers that still have official support or updates.</li></ul><p>Run the Rollup command again:</p><pre>$ rollup -c</pre><p>Check the generated bundles. Both the cjs and the umd format are using ES5 syntax. That&#39;s because of our query on .browerslistrc are applied both to the cjs and umd output. Some of the browsers from that query are still not supporting const and arrow function syntax that we use. You can check all of the browsers that matched our query on this website: <a href="https://browserl.ist/?q=last+1+version%2C%3E+5%25%2C+not+dead">browserl.ist</a>.</p><p>So how can we use a different browserslist query for cjs and umd format? For the CommonJS format we want to use:</p><pre>maintained node versions</pre><p>While for the UMD format, we’d like to use:</p><pre>last 1 version<br>&gt; 5%<br>not dead</pre><p>Remember that we’re allowed to have <a href="https://risanb.com/code/bundling-your-javascript-library-with-rollup/#multiple-inputs">multiple inputs</a> in rollup.config.js:</p><pre>// rollup.config.js<br>import babel from &#39;rollup-plugin-babel&#39;;<br>import commonjs from &#39;rollup-plugin-commonjs&#39;;<br>import resolve from &#39;rollup-plugin-node-resolve&#39;;</pre><pre>export default [<br>  {<br>    input: &#39;src/main.js&#39;,<br>    output: {<br>      file: &#39;dist/cjs.js&#39;,<br>      format: &#39;cjs&#39;<br>    },<br>    plugins: [<br>      resolve(),<br>      commonjs(),<br>      babel({<br>        exclude: &#39;node_modules/**&#39;,<br>        babelrc: false,<br>        presets: [<br>          [<br>            &#39;@babel/env&#39;,<br>            {<br>              modules: false,<br>              useBuiltIns: &quot;usage&quot;,<br>              targets: &#39;maintained node versions&#39;<br>            }<br>          ]<br>        ]<br>      })<br>    ]<br>  },<br>  {<br>    input: &#39;src/main.js&#39;,<br>    output: {<br>      file: &#39;dist/umd.js&#39;,<br>      format: &#39;umd&#39;,<br>      name: &#39;eatFruit&#39;<br>    },<br>    plugins: [<br>      resolve(),<br>      commonjs(),<br>      babel({<br>        exclude: &#39;node_modules/**&#39;<br>      })<br>    ]<br>  }<br>];</pre><p>Note that on the cjs section, we pass babelrc: false to the babel plugin. This way we can override the configurations that are set on the src/.babelrc file.</p><pre>babel({<br>  exclude: &#39;node_modules/**&#39;,<br>  babelrc: false,<br>  presets: [<br>    [<br>      &#39;@babel/env&#39;,<br>      {<br>        modules: false,<br>        useBuiltIns: &quot;usage&quot;,<br>        targets: &#39;maintained node versions&#39;<br>      }<br>    ]<br>  ]<br>})</pre><p>Don’t forget to update the .browerslistrc too:</p><pre>last 1 version<br>&gt; 5%<br>not dead</pre><p>The umd format will still use the query set on the .browerslistrc. But the cjs format will now use the maintained node versions query instead. Run the bundle command again:</p><pre>$ rollup -c</pre><p>You should now find that the umd format are using ES 2015 syntax again.</p><h3>Minifying Bundle</h3><p>For browser usage, the library author often offers a minified version of the library. We can use the <a href="https://github.com/TrySound/rollup-plugin-terser">rollup-plugin-terser</a> to minify our umd bundle. Let&#39;s install it:</p><pre>$ npm i rollup-plugin-terser -D</pre><pre># Or if you use Yarn<br>$ yarn add rollup-plugin-terser -D</pre><p>We’ll keep the non-minified version of the umd bundle. So we just need to add a similar umd config but with the rollup-plugin-terser addition.</p><pre>// rollup.config.js<br>import babel from &#39;rollup-plugin-babel&#39;;<br>import commonjs from &#39;rollup-plugin-commonjs&#39;;<br>import resolve from &#39;rollup-plugin-node-resolve&#39;;<br>import { terser } from &#39;rollup-plugin-terser&#39;;</pre><pre>export default [<br>  {<br>    input: &#39;src/main.js&#39;,<br>    output: {<br>      file: &#39;dist/cjs.js&#39;,<br>      format: &#39;cjs&#39;<br>    },<br>    plugins: [<br>      resolve(),<br>      commonjs(),<br>      babel({<br>        exclude: &#39;node_modules/**&#39;,<br>        babelrc: false,<br>        presets: [<br>          [<br>            &#39;@babel/env&#39;,<br>            {<br>              modules: false,<br>              useBuiltIns: &quot;usage&quot;,<br>              targets: &#39;maintained node versions&#39;<br>            }<br>          ]<br>        ]<br>      })<br>    ]<br>  },<br>  {<br>    input: &#39;src/main.js&#39;,<br>    output: {<br>      file: &#39;dist/umd.js&#39;,<br>      format: &#39;umd&#39;,<br>      name: &#39;eatFruit&#39;<br>    },<br>    plugins: [<br>      resolve(),<br>      commonjs(),<br>      babel({<br>        exclude: &#39;node_modules/**&#39;<br>      })<br>    ]<br>  },<br>  {<br>    input: &#39;src/main.js&#39;,<br>    output: {<br>      file: &#39;dist/umd.min.js&#39;,<br>      format: &#39;umd&#39;,<br>      name: &#39;eatFruit&#39;<br>    },<br>    plugins: [<br>      resolve(),<br>      commonjs(),<br>      babel({<br>        exclude: &#39;node_modules/**&#39;<br>      }),<br>      terser()<br>    ]<br>  }<br>];</pre><p>Once it’s added, let’s bundle our main.js file again:</p><pre>$ rollup -c</pre><p>We should now get a new bundle named umd.min.js. If you check this bundle, you&#39;ll see that the code is minified.</p><h3>Publishing Our Bundles</h3><p>Let’s wrap this up by publishing our bundles to NPM. First, let’s install rollup as our dev dependency:</p><pre>npm i rollup -D</pre><pre># Or if you use Yarn.<br>yarn add rollup -D</pre><p>All this time we use the globally installed rollup to bundle our library. It&#39;s not the right approach. Other people might contribute to our library. It&#39;s possible that they have a different Rollup version, or even worse they might not have Rollup installed at all.</p><p>We might also use a CI pipeline to automate package publishing. And the server might not have Rollup installed. This way we can make sure every contributor or the CI server uses the same version of Rollup.</p><h4>Update Our package.json File</h4><p>Let’s update our package.json file too:</p><pre>{<br>  &quot;name&quot;: &quot;eat-fruit&quot;,<br>  &quot;description&quot;: &quot;Package to print some random fruit I eat.&quot;,<br>  &quot;version&quot;: &quot;0.0.1&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;main&quot;: &quot;dist/eat-fruit.cjs.js&quot;,<br>  &quot;browser&quot;: &quot;dist/eat-fruit.umd.js&quot;,<br>  &quot;module&quot;: &quot;dist/eat-fruit.es.js&quot;,<br>  &quot;engines&quot;: {<br>    &quot;node&quot;: &quot;&gt;= 6&quot;<br>  },<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;rollup -c&quot;,<br>    &quot;prepublishOnly&quot;: &quot;npm run build&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;lodash&quot;: &quot;^4.17.11&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@babel/core&quot;: &quot;^7.1.2&quot;,<br>    &quot;@babel/preset-env&quot;: &quot;^7.1.0&quot;,<br>    &quot;rollup&quot;: &quot;^0.66.6&quot;,<br>    &quot;rollup-plugin-babel&quot;: &quot;^4.0.3&quot;,<br>    &quot;rollup-plugin-commonjs&quot;: &quot;^9.2.0&quot;,<br>    &quot;rollup-plugin-node-resolve&quot;: &quot;^3.4.0&quot;,<br>    &quot;rollup-plugin-terser&quot;: &quot;^3.0.0&quot;<br>  }<br>}</pre><blockquote><em>🚨 IMPORTANT</em></blockquote><blockquote><em>The </em><em>name property in the </em><em>package.json is the most important one. It&#39;s the name of your package. </em><strong><em>It must be unique</em></strong><em>. I already used the </em><em>eat-fruit name. You have to choose your own unique package name. Use the </em><a href="https://www.npmjs.com/"><em>NPM</em></a><em> search feature to check for the availability.</em></blockquote><blockquote><em>Read more about the </em><em>name rules in the </em><a href="https://docs.npmjs.com/files/package.json#name"><em>documentation</em></a><em>.</em></blockquote><p>Note that our dependencies’ version might be different, and that’s okay. Also notice the main, module, and browser properties:</p><pre>{<br>  ...<br>  &quot;main&quot;: &quot;dist/eat-fruit.cjs.js&quot;,<br>  &quot;browser&quot;: &quot;dist/eat-fruit.umd.js&quot;,<br>  &quot;module&quot;: &quot;dist/eat-fruit.es.js&quot;,<br>  ...<br>}</pre><ul><li>main: This is the primary entry point for our package. We set it to the CommonJS bundle format.</li><li>browser: This is the bundle for the browser usage.</li><li>module: This is the ES bundle that meant to be used by the ES-module-aware tools like Rollup or Webpack 2+.</li></ul><p>We also add some scripts:</p><pre>{<br>  ...<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;rollup -c&quot;,<br>    &quot;prepublishOnly&quot;: &quot;npm run build&quot;<br>  },<br>  ...<br>}</pre><ul><li>build: Run the Rollup bundle command.</li><li>prepublishOnly: This script will be run before our library is published. It&#39;s to make sure that we publish the latest bundles.</li></ul><h4>Updating the Rollup Config File</h4><p>Let’s update our Rollup config file to generate the es module too. We also use the package.json file to specify the output path for each format.</p><pre>// rollup.config.js<br>import babel from &#39;rollup-plugin-babel&#39;;<br>import commonjs from &#39;rollup-plugin-commonjs&#39;;<br>import resolve from &#39;rollup-plugin-node-resolve&#39;;<br>import { terser } from &#39;rollup-plugin-terser&#39;;</pre><pre>import pkg from &#39;./package.json&#39;;</pre><pre>export default [<br>  {<br>    input: &#39;src/main.js&#39;,<br>    output: {<br>      file: pkg.main,<br>      format: &#39;cjs&#39;<br>    },<br>    plugins: [<br>      resolve(),<br>      commonjs(),<br>      babel({<br>        exclude: &#39;node_modules/**&#39;,<br>        babelrc: false,<br>        presets: [<br>          [<br>            &#39;@babel/env&#39;,<br>            {<br>              modules: false,<br>              useBuiltIns: &quot;usage&quot;,<br>              targets: &#39;maintained node versions&#39;<br>            }<br>          ]<br>        ]<br>      })<br>    ]<br>  },<br>  {<br>    input: &#39;src/main.js&#39;,<br>    output: {<br>      file: pkg.browser,<br>      format: &#39;umd&#39;,<br>      name: &#39;eatFruit&#39;<br>    },<br>    plugins: [<br>      resolve(),<br>      commonjs(),<br>      babel({<br>        exclude: &#39;node_modules/**&#39;<br>      })<br>    ]<br>  },<br>  {<br>    input: &#39;src/main.js&#39;,<br>    output: {<br>      file: pkg.browser.replace(/\.js$/, &#39;.min.js&#39;),<br>      format: &#39;umd&#39;,<br>      name: &#39;eatFruit&#39;<br>    },<br>    plugins: [<br>      resolve(),<br>      commonjs(),<br>      babel({<br>        exclude: &#39;node_modules/**&#39;<br>      }),<br>      terser()<br>    ]<br>  },<br>  {<br>    input: &#39;src/main.js&#39;,<br>    output: {<br>      file: pkg.module,<br>      format: &#39;es&#39;<br>    },<br>    plugins: [<br>      resolve(),<br>      commonjs(),<br>      babel({<br>        exclude: &#39;node_modules/**&#39;<br>      })<br>    ]<br>  }<br>];</pre><p>Let’s try to bundle our library:</p><pre>$ npm run build</pre><pre># Or if you use Yarn<br>$ yarn build</pre><p>We should now have four build files within the dist directory:</p><ul><li>eat-fruit.cjs.js</li><li>eat-fruit.ed.js</li><li>eat-fruit.umd.js</li><li>eat-fruit.umd.min.js</li></ul><h4>Add .npmignore File</h4><p>We only want to distribute the generated bundle files. We don’t need to include the src directory or the Rollup configuration file. We can create .npmignore file to exclude files or directories that we don&#39;t want to distribute to our users.</p><pre>#.npmignore<br>.browserslistrc<br>rollup.config.js<br>src<br>yarn.lock</pre><p>Note that the node_modules directory will be ignored automatically, so we don&#39;t have to add it into the .npmignore. Note that the package.json, README, LICENSE, and CHANGELOG files will always be included. Even if we list them in the .npmignore.</p><h4>Login To NPM</h4><p>To publish a package, you must be registered as an <a href="https://www.npmjs.com/">NPM</a> user. If you’re not a user create a new account here: <a href="https://www.npmjs.com/signup">NPM Sign Up</a>.</p><p>Next, log in to NPM using your terminal:</p><pre>$ npm login</pre><p>Type the following command to check whether you’re logged in or not:</p><pre>$ npm whoami</pre><h3>Publishing</h3><p>Before publishing your package, make sure that your bundle can be installed and working properly. You can install your package locally. Create a directory somewhere outside of your project directory.</p><p>Now, within that test directory, create an empty package.json file:</p><pre>$ <em>echo</em> {} &gt; package.json</pre><p>You can then install your package by passing the path to your package project directory:</p><pre>$ npm i ../path/to/package-directory</pre><pre># Or if you use Yarn<br>$ yarn add ../path/to/package-directory</pre><p>You can verify further by opening the node-repl and try to require your package:</p><pre>$ node</pre><pre>&gt; const <em>eatFruit</em> = require(&#39;eat-fruit&#39;);<br>undefined<br>&gt; eatFruit();<br>I eat 🍉.</pre><p>If all goes well, you’re ready to publish your package! Run the following command to:</p><pre>$ npm publish</pre><h3>Summary</h3><p>Congratulation 🎉 You’ve made it until the end! Let’s recap what you’ve learned so far:</p><ul><li>Rollup offers various output formats: amd, cjs, es, umd, and iife.</li><li>We can configure Rollup through a configuration file.</li><li>Rollup has a tree-shaking feature that can eliminate unused code from the final bundle.</li><li>Many plugins are available to extend Rollup capability, we tried several of them: resolving external NPM package, transforming CommonJS module, integration with Babel, and plugin for minifying the bundle.</li><li>We also learn how to publish our package to NPM registry.</li></ul><p>You can get the source code for this tutorial on my Github repository: <a href="https://github.com/risan/eat-fruit">github.com/risan/eat-fruit</a>. And don’t forget to check out the official <a href="https://rollupjs.org/guide/en">Rollup guide</a>.</p><p><em>Originally published at </em><a href="https://risanb.com/code/bundling-your-javascript-library-with-rollup/"><em>https://risanb.com</em></a><em> on November 4, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73be9620be09" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risan/bundling-your-javascript-library-with-rollup-73be9620be09">Bundling Your JavaScript Library with Rollup</a> was originally published in <a href="https://medium.com/risan">Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue Chart Component with Chart.js]]></title>
            <link>https://medium.com/risan/vue-chart-component-with-chart-js-db85a2d21288?source=rss----b42a56310d1c---4</link>
            <guid isPermaLink="false">https://medium.com/p/db85a2d21288</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[chartjs]]></category>
            <dc:creator><![CDATA[Risan Bagja]]></dc:creator>
            <pubDate>Wed, 31 Oct 2018 20:01:45 GMT</pubDate>
            <atom:updated>2021-09-12T11:59:08.448Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCoqJKb-QnoxWFPsjyqU0g.png" /></figure><p>Chart.js is an amazing chart library for JavaScript. It’s modern and performant; built on top of the HTML5 canvas. It includes 8 different chart types which super easy to extend and configure. On top of it all, the generated chart just looks beautiful.</p><p>Last night I did some tinkering to integrate Chart.js within the existing Vue code base. So, how can we do that? If you want, there’s actually a wrapper for Chart.js already available for Vue: <a href="https://vue-chartjs.org/">vue-chartjs</a>. If you take a look at the vue-chartjs <a href="https://github.com/apertureless/vue-chartjs">source code</a>, it’s actually pretty simple and straightforward. So let’s try to build one ourself!</p><p>You can check out the final working source code on <a href="https://github.com/risan/vue-chart-example">Github</a>. You can also visit the demo here: <a href="https://risan.github.io/vue-chart-example/">risan.github.io/vue-chart-example</a>.</p><h3>Creating New Project</h3><p>On this tutorial, I will use <a href="https://cli.vuejs.org/">Vue CLI</a> version 3 to scaffold my project. But of course you can always use your own build system as long as it can handle the Vue <a href="https://vuejs.org/v2/guide/single-file-components.html">Single File Component</a> — if not you have to slightly modify the component declaration by inlining the &lt;template&gt;’s content into your template property.</p><p>If you want to use Vue CLI and doesn’t have one installed on your computer, run the following command on your terminal to install it:</p><pre>$ npm install -g @vue/cli</pre><pre># Or if you prefer to use yar.<br>$ yarn global add @vue/cli</pre><p>Next, let’s create a new project with Vue CLI:</p><pre>$ vue create vue-chart-example</pre><p>You’ll be prompted to choose the preset, I choose the default one which will configure Babel and ESLint for us. Then you’ll be asked to choose the package manager to use: Yarn or the default NPM. The installation should be started, just wait until your project is created.</p><p>You’ll get a similar output upon a successful project creation:</p><pre>🎉  Successfully created project vue-chart-example.<br>👉  Get started with the following commands:</pre><pre>$ cd vue-chart-example<br>$ yarn serve</pre><p>Now, let’s run our project:</p><pre># Go the project&#39;s directory<br>$ cd vue-chart-example</pre><pre># Build and run the project.<br>$ npm run serve</pre><pre># Or if you use yarn.<br>$ yarn serve</pre><p>Once the development server is running, open the <a href="http://localhost:8080/">localhost:8080</a> address on your browser. You should see your Vue project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*x2Rqx_sHbaDYjfaj.png" /></figure><p>Press CTRL + c to stop the development server. We’re going to code from scratch, so we won’t need any of the provided boilerplate code on src directory. Let’s delete them!</p><h3>Getting Started with Chart.js</h3><p>Open your terminal, and type the following command to install Chart.js:</p><pre>npm install chart.js</pre><pre># Or if you prefer to use Yarn.<br>yarn add chart.js</pre><blockquote><em>Note: if you use NPM prior to version 5, you need to provide the </em><em>--save option to automatically update the </em><em>dependencies list on your </em><em>package.json file.</em></blockquote><p>Here’s the constructor’s signature on how to initialize a new Chart.js instance:</p><pre>new Chart(context [CanvasRenderingContext2D|Element|String], {<br>  type: String,<br>  data: Object,<br>  options: Object<br>});</pre><ul><li>context: It can either be an instance of <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">CanvasRenderingContext2D</a> interface, an <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element">Element</a>, or a String of the canvas’s id.</li><li>type: This is the chart’s type like line, bar, or pie. Check out the <a href="http://www.chartjs.org/docs/latest/charts/">Charts Section</a> on the docs for a complete reference.</li><li>data: It will contain the datasets property which is the data that will be used to plot the chart.</li><li>options: Chart configuration options, like responsiveness, legend, axes, title, etc.</li></ul><h3>Plot a Line Chart</h3><p>Confused? Let’s create some line chart with Chart.js! Open the public/index.html file, then add a new &lt;canvas&gt; tag within the &lt;body&gt;. This canvas tag is where we will plot the chart.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  ...<br>  &lt;body&gt;<br>    &lt;div id=&quot;app&quot;&gt;&lt;/div&gt;<br><br>    &lt;!-- Put canvas tag here. --&gt;<br>    &lt;canvas id=&quot;my-chart&quot; width=&quot;500&quot; height=&quot;300&quot;&gt;&lt;/canvas&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now let’s recreate the src/main.js file. This is the default entry point for the project scaffolded by the Vue CLI.</p><pre>import Chart from &#39;chart.js&#39;;<br><br>new Chart(document.getElementById(&#39;my-chart&#39;), {<br>  type: &#39;line&#39;,<br>  data: {<br>    labels: [&#39;Jan&#39;, &#39;Feb&#39;, &#39;Mar&#39;, &#39;Apr&#39;, &#39;May&#39;],<br>    datasets: [<br>      {<br>        label: &#39;2018 Sales&#39;,<br>        data: [300, 700, 450, 750, 450]<br>      }<br>    ]<br>  }<br>});</pre><p>Note that we don’t pass any options property for now. Let’s run our project again:</p><pre>$ npm run serve<br><br># Or<br>$ yarn serve</pre><p>You should now see your line chart plotted on the browser!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OFOAJGdOwhM_ZPEd.png" /></figure><p>Note that even though we set the width to 500 and the height to 300, the generated chart will occupy the entire screen. That’s because, by default, Chart.js will generate a responsive chart that will occupy its parent container. You may also notice that even though it’s stretched out, by default Chart.js will still maintain the original aspect ratio (5:3).</p><p>If this is not the way you want it to be, you can always override this behavior. Read more about <a href="http://www.chartjs.org/docs/latest/general/responsive.html">responsive chart</a>.</p><h4>Data Format</h4><p>As you may see the data property holds a datasets property. This is an array of data that we want to plot on the chart. By default, on line-chart, these data will be represented on y axis (vertical axis). These data can also be formatted in {x, y} format:</p><pre>{<br>  label: &#39;2018 Sales&#39;,<br>  data: [<br>    { x: 0, y: 300 },<br>    { x: 1, y: 700 },<br>    { x: 2, y: 450 },<br>    { x: 3, y: 750 },<br>    { x: 4, y: 450 }<br>  ]<br>}</pre><h4>Labels</h4><p>On line-chart, by default the data.labels property will be used as the label on x axis (horizontal axis). Each item on data.datasets will be paired with the item on data.labels.</p><p>We can also configure the labels by passing it into options.scales.xAxes options instead:</p><pre>import Chart from &#39;chart.js&#39;;<br><br>new Chart(document.getElementById(&#39;my-chart&#39;), {<br>  type: &#39;line&#39;,<br>  data: {<br>    datasets: [<br>      {<br>        label: &#39;2018 Sales&#39;,<br>        data: [300, 700, 450, 750, 450]<br>      }<br>    ]<br>  },<br>  options: {<br>    scales: {<br>      xAxes: [{<br>        type: &#39;category&#39;,<br>        labels: [&#39;Jan&#39;, &#39;Feb&#39;, &#39;Mar&#39;, &#39;Apr&#39;, &#39;May&#39;],<br>      }]<br>    }<br>  }<br>});</pre><h4>Multiple Datasets</h4><p>We can, of course, provide as many datasets as we like. For this example we’ll add another dataset for <strong>2017 Sales</strong>:</p><pre>new Chart(document.getElementById(&#39;my-chart&#39;), {<br>  type: &#39;line&#39;,<br>  data: {<br>    labels: [&#39;Jan&#39;, &#39;Feb&#39;, &#39;Mar&#39;, &#39;Apr&#39;, &#39;May&#39;],<br>    datasets: [<br>      {<br>        label: &#39;2018 Sales&#39;,<br>        data: [300, 700, 450, 750, 450]<br>      },<br>      {<br>        label: &#39;2017 Sales&#39;,<br>        data: [600, 550, 750, 250, 700]<br>      }<br>    ]<br>  }<br>});</pre><p>Now, if we visit the project’s URL, we should see the similar result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W2mPQ26-7kv_hoz0.png" /></figure><h3>Configuring Our Line Chart</h3><h4>Coloring The Chart</h4><p>Right now it’s hard to differentiate between the <strong>2018 Sales</strong> and the <strong>2017 Sales</strong> since both have the same color. We can configure the color for each dataset by providing the backgroundColor and borderColor to each datasets item:</p><pre>new Chart(document.getElementById(&#39;my-chart&#39;), {<br>  type: &#39;line&#39;,<br>  data: {<br>    labels: [&#39;Jan&#39;, &#39;Feb&#39;, &#39;Mar&#39;, &#39;Apr&#39;, &#39;May&#39;],<br>    datasets: [<br>      {<br>        label: &#39;2018 Sales&#39;,<br>        borderColor: &#39;rgba(50, 115, 220, 0.5)&#39;,<br>        backgroundColor: &#39;rgba(50, 115, 220, 0.1)&#39;,<br>        data: [300, 700, 450, 750, 450]<br>      },<br>      {<br>        label: &#39;2017 Sales&#39;,<br>        borderColor: &#39;rgba(255, 56, 96, 0.5)&#39;,<br>        backgroundColor: &#39;rgba(255, 56, 96, 0.1)&#39;,<br>        data: [600, 550, 750, 250, 700]<br>      }<br>    ]<br>  }<br>});</pre><p>Both borderColor and backgroundColor receive a string of color which can be represented in the rgba format—similar to what we have in CSS:</p><pre>rgba(red, green, blue, alpha)</pre><p>If we check our project on the browser, we should now have a colorful chart like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b-Hx05Pxy_mXFo9h.png" /></figure><h4>Configuring the Y-Axis Label</h4><p>You may have noticed that the y-axis starts from 300 instead of 0. That’s because Chart.js will automatically use the lowest value on our datasets as the starting point. If that’s not what you want, we can override this by providing the beginAtZero option:</p><pre>new Chart(document.getElementById(&#39;my-chart&#39;), {<br>  type: &#39;line&#39;,<br>  data: {<br>    // Omitted...<br>  },<br>  options: {<br>    scales: {<br>      yAxes: [{<br>        ticks: {<br>          beginAtZero: true<br>        }<br>      }]<br>    }<br>  }<br>});</pre><p>Our line chart should now look like the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fluJJWx5uFF8xt_-.png" /></figure><p>Also, wouldn’t it be nice if we can put some dollar or other currency symbols on the y-axis? Let’s put it then! But first, let’s pull another library for number formatting: <a href="http://numeraljs.com/">Numeral.js</a>. So we don’t have to deal with the currency formatting on this tutorial 😛.</p><pre>$ npm install numeral<br><br># Or if you use Yarn<br>$ yarn add numeral</pre><p>On ticks property, we can provide a callback option. This is a function that should return a custom axis label. This callback function will receive three arguments, the first one is the actual axis value that we can use:</p><pre>import Chart from &#39;chart.js&#39;;<br>import numeral from &#39;numeral&#39;;<br><br>new Chart(document.getElementById(&#39;my-chart&#39;), {<br>  type: &#39;line&#39;,<br>  data: {<br>    // Omitted...<br>  },<br>  options: {<br>    scales: {<br>      yAxes: [{<br>        ticks: {<br>          beginAtZero: true,<br>          callback: value =&gt; numeral(value).format(&#39;$0,0&#39;)<br>        }<br>      }]<br>    }<br>  }<br>});</pre><p>The y-axis label should now have the currency symbol. Read more about all available <a href="http://www.chartjs.org/docs/latest/axes/">axes configuration</a> and <a href="http://www.chartjs.org/docs/latest/axes/labelling.html">labelling</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/0*9EKYTrRPVdHeH-cS.png" /></figure><h4>Configuring the Tooltip</h4><p>Even though we already formatted the y-axis label, but if you hover or click on any of the data points, the displayed y-axis value is still not formatted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l5mHWA9p9r0n2El2.png" /></figure><p>To get around this, we have to provide a function to the tooltips.callbacks.label options like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05c11a03e898c6d381356247a617ac3f/href">https://medium.com/media/05c11a03e898c6d381356247a617ac3f/href</a></iframe><p>This label callback, received two arguments:</p><ul><li>tooltipItem: An object of the selected data point, we can get the y-axis value by accessing the tooltipItem.yLabel.</li><li>data: It’s the entire array of data property provided to the constructor. Combined with the tooltipItem.datasetIndex value, we can then get the selected dataset’s label (“2018 Sales” and “2017 Sales”).</li></ul><p>If we check our project on the browser again, we should now have a nicely formatted data displayed on our tooltip.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yx01NMNF6Ac3WalV.png" /></figure><p>In our case, wouldn’t it be nice if the tooltip can also display the sales amount from both of the datasets? To achieve this, we simply have to set the tooltip’s mode to index:</p><pre>new Chart(document.getElementById(&#39;my-chart&#39;), {<br>  type: &#39;line&#39;,<br>  data: {<br>    // Omitted...<br>  },<br>  options: {<br>    scales: {<br>      // Omitted...<br>    },<br>    tooltips: {<br>      mode: &#39;index&#39;,<br>      callbacks: {<br>        // Omitted...<br>      }<br>    }<br>  }<br>});</pre><p>Now, when we hover to some data point, the tooltip should now display the sales amount from both datasets. Read more about all available <a href="http://www.chartjs.org/docs/latest/configuration/tooltip.html">tooltip configuration</a> and <a href="http://www.chartjs.org/docs/latest/general/interactions/modes.html#interaction-modes">interaction modes</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jpo85ZI70ZzQFHUI.png" /></figure><h3>Making it Prettier</h3><p>Before we start digging into the Vue stuff. Let’s make our web page layout a bit prettier. You can skip this part if you want. I’ll use <a href="https://bulma.io/">Bulma</a> for styling up our page.</p><p>Open the public/index.html file again, and let’s add some simple <a href="https://bulma.io/documentation/components/navbar/">navbar</a> and put our &lt;canvas&gt; tag within a <a href="https://bulma.io/documentation/elements/box/">box</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/287e0d0c8d9cb8aa8f2105c6192e9cc1/href">https://medium.com/media/287e0d0c8d9cb8aa8f2105c6192e9cc1/href</a></iframe><p>I won’t go into detail. It just some basic Bulma UI elements. Now we should have some decent looking layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kg89b0G6YoigpohK.png" /></figure><h3>Integrating Chart.js into Vue</h3><p>Now, let’s work on the real issue here. How can we integrate our chart into a Vue application?</p><h3>Setting Up the Vue Application</h3><p>Let’s recreate the Vue application that once we’ve deleted before. Open up the public/index.html file again. Remove the &lt;canvas&gt; tag and the entire box element. Then add back the &lt;div id=&quot;app&quot;&gt;&lt;/div&gt;, this is where our application root will be mounted.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    ...<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    ...<br>    &lt;nav class=&quot;navbar is-primary&quot;&gt;<br>      &lt;div class=&quot;container&quot;&gt;<br>        &lt;div class=&quot;navbar-brand&quot;&gt;<br>          &lt;a class=&quot;navbar-item&quot; href=&quot;/&quot;&gt;<br>            &lt;h1&gt;Vue Chart Example&lt;/h1&gt;<br>          &lt;/a&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/nav&gt;<br>    &lt;section class=&quot;section&quot;&gt;<br>      &lt;div class=&quot;container&quot;&gt;<br>        &lt;div id=&quot;app&quot;&gt;&lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/section&gt;<br>    &lt;!-- built files will be auto injected --&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Also, add back the src/App.vue file again, this is where we’ll put our Vue application root code.</p><pre>&lt;template&gt;<br>  &lt;div class=&quot;box&quot;&gt;<br>    &lt;h2 class=&quot;title is-5&quot;&gt;Monthly Sales Chart&lt;/h2&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>export default {<br>  name: &#39;app&#39;<br>}<br>&lt;/script&gt;</pre><p>Next, let’s replace our main.js file to run the main App.vue component:</p><pre>import Vue from &#39;vue&#39;;<br>import App from &#39;./App&#39;;<br><br>new Vue({<br>  render: h =&gt; h(App)<br>}).$mount(&#39;#app&#39;);</pre><p>Our chart should now be gone. It’s just a title and someempty box now. Let’s put back our chart!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vS3WmGaUXGTainUb.png" /></figure><h3>The Monthly Sales Chart Component</h3><p>Let’s create a new Vue component for our monthly sales chart. Create a new file named ‘MonthlySalesChart.vue’ and store it within the src/components directory.</p><pre>&lt;template&gt;<br>  &lt;canvas ref=&quot;myChart&quot; width=&quot;500&quot; height=&quot;300&quot;&gt;&lt;/canvas&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>import Chart from &#39;chart.js&#39;;<br><br>export default {<br>  name: &#39;monthly-sales-chart&#39;,<br>  mounted() {<br>    new Chart(this.$refs.myChart, {<br>      type: &#39;line&#39;,<br>      data: {<br>        labels: [&#39;Jan&#39;, &#39;Feb&#39;, &#39;Mar&#39;, &#39;Apr&#39;, &#39;May&#39;],<br>        datasets: [<br>          {<br>            label: &#39;2018 Sales&#39;,<br>            data: [300, 700, 450, 750, 450]<br>          }<br>        ]<br>      }<br>    });<br>  }<br>}<br>&lt;/script&gt;</pre><p>You may have noticed, that actually it’s just a code from our very first line chart. Notice how we put the Chart.js instantiation within the Vue <a href="https://vuejs.org/v2/api/#mounted">mounted hook</a>. That’s because Chart.js needs an access to the actual DOM element to plot the chart. And the &lt;canvas&gt; element will only be available right after this component is mounted.</p><p>Also, notice how we’re making use of the <a href="https://vuejs.org/v2/api/#ref">$refs</a> property to get the reference to the canvas element.</p><p>Now, go back to the src/App.vue file again. Let’s register and use our new MonthlySalesChart component:</p><pre>&lt;template&gt;<br>  &lt;div class=&quot;box&quot;&gt;<br>    &lt;h2 class=&quot;title is-5&quot;&gt;Monthly Sales Chart&lt;/h2&gt;<br>    &lt;monthly-sales-chart&gt;&lt;/monthly-sales-chart&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>import MonthlySalesChart from &#39;./components/MonthlySalesChart&#39;;<br><br>export default {<br>  name: &#39;app&#39;,<br>  components: {<br>    MonthlySalesChart<br>  }<br>}<br>&lt;/script&gt;</pre><p>If things go well, we should see the line chart again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DAjpOUUK9wnCv-vI.png" /></figure><h3>The Line Chart Component</h3><p>Let’s take our Vue and Chart.js integration even further. We can abstract away the MonthlySalesChart component into a more general component: LineChart. Create a new file named LineChart.vue and store it within the src/components directory.</p><pre>&lt;template&gt;<br>  &lt;canvas ref=&quot;myChart&quot; :width=&quot;width&quot; :height=&quot;height&quot;&gt;&lt;/canvas&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>import Chart from &#39;chart.js&#39;;<br><br>export default {<br>  name: &#39;monthly-sales-chart&#39;,<br>  props: {<br>    // The canvas&#39;s width.<br>    width: {<br>      type: Number,<br>      validator: value =&gt; value &gt; 0<br>    },<br><br>    // The canvas&#39;s height.<br>    height: {<br>      type: Number,<br>      validator: value =&gt; value &gt; 0<br>    },<br><br>    // The chart&#39;s data.labels<br>    labels: Array,<br><br>    // The chart&#39;s data.datasets<br>    datasets: {<br>      type: Array,<br>      required: true<br>    },<br><br>    // The chart&#39;s options.<br>    options: Object<br>  },<br>  mounted() {<br>    new Chart(this.$refs.myChart, {<br>      type: &#39;line&#39;,<br>      data: {<br>        labels: this.labels,<br>        datasets: this.datasets<br>      },<br>      options: this.options<br>    });<br>  }<br>}<br>&lt;/script&gt;</pre><p>Notice how we turn every configurable value into a component’s props:</p><ul><li>width: It’s the canvas’s width in pixel.</li><li>height: The canvas’s height in pixel.</li><li>labels: It’s the axis labels that will be passed to Chart.js constructor as data.labels. It’s not required since it’s possible for us to pass it as an options too.</li><li>datasets: The only required props, since this contains the data that we want to plot using Chart.js. This props will be passed to Chart.js constructor as data.datasets.</li><li>options: Finally this is the configuration options for the Chart.js.</li></ul><p>Let’s modify our src/component/MonthlySalesChart.vue file to use this new LineChart component.</p><pre>&lt;template&gt;<br>  &lt;line-chart<br>    :width=&quot;500&quot;<br>    :height=&quot;300&quot;<br>    :labels=&quot;[&#39;Jan&#39;, &#39;Feb&#39;, &#39;Mar&#39;, &#39;Apr&#39;, &#39;May&#39;]&quot;<br>    :datasets=&quot;$options.datasets&quot;<br>  &gt;&lt;/line-chart&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>import LineChart from &#39;./LineChart&#39;;<br><br>const datasets = [<br>  {<br>    label: &#39;2018 Sales&#39;,<br>    data: [300, 700, 450, 750, 450]<br>  }<br>];<br><br>export default {<br>  name: &#39;monthly-sales-chart&#39;,<br>  datasets,<br>  components: {<br>    LineChart<br>  }<br>}<br>&lt;/script&gt;</pre><p>Notice how we put the datasets constant as a custom component’s property instead of part of the usual component’s data. That’s because up until this point our datasets is static and no need to be reactive. So, there’s no use to register it as a data property. We can use the <a href="https://vuejs.org/v2/api/#vm-options">$options</a> to access the custom property.</p><p>If things go well, we should still have the same exact chart like before.</p><h3>Put Back Chart Datasets and Options</h3><p>Let’s put back all previous datasets and Chart.js options to our MonthlySalesChart.vue file:</p><pre>&lt;template&gt;<br>  &lt;line-chart<br>    :width=&quot;500&quot;<br>    :height=&quot;300&quot;<br>    :labels=&quot;[&#39;Jan&#39;, &#39;Feb&#39;, &#39;Mar&#39;, &#39;Apr&#39;, &#39;May&#39;]&quot;<br>    :datasets=&quot;$options.datasets&quot;<br>    :options=&quot;$options.options&quot;<br>  &gt;&lt;/line-chart&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>import numeral from &#39;numeral&#39;;<br>import LineChart from &#39;./LineChart&#39;;<br><br>const datasets = [<br>  {<br>    label: &#39;2018 Sales&#39;,<br>    borderColor: &#39;rgba(50, 115, 220, 0.5)&#39;,<br>    backgroundColor: &#39;rgba(50, 115, 220, 0.1)&#39;,<br>    data: [300, 700, 450, 750, 450]<br>  },<br>  {<br>    label: &#39;2017 Sales&#39;,<br>    borderColor: &#39;rgba(255, 56, 96, 0.5)&#39;,<br>    backgroundColor: &#39;rgba(255, 56, 96, 0.1)&#39;,<br>    data: [600, 550, 750, 250, 700]<br>  }<br>];<br><br>const options = {<br>  scales: {<br>    yAxes: [{<br>      ticks: {<br>        beginAtZero: true,<br>        callback: value =&gt; numeral(value).format(&#39;$0,0&#39;)<br>      }<br>    }]<br>  },<br>  tooltips: {<br>    mode: &#39;index&#39;,<br>    callbacks: {<br>      label(tooltipItem, data) {<br>        const label = data.datasets[tooltipItem.datasetIndex].label;<br>        const value = numeral(tooltipItem.yLabel).format(&#39;$0,0&#39;);<br><br>        return `${label}: ${value}`;<br>      }<br>    }<br>  }<br>};<br><br>export default {<br>  name: &#39;monthly-sales-chart&#39;,<br>  datasets,<br>  options,<br>  components: {<br>    LineChart<br>  }<br>}<br>&lt;/script&gt;</pre><p>We should now see the <strong>Sales 2018</strong> and the <strong>Sales 2017</strong> datasets again. The chart that we used to have: two different colors, currency formatted y-axis, and tooltip!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IaKTUTrnROOV4vZk.png" /></figure><h3>Reactive Chart</h3><p>Let’s do some experiment with reactive datasets. Open up the src/components/MonthlySalesChart.vue. Then add two new checkboxes that will toggle which datasets to display on the chart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6856bc5ba2c51d0d2a8d2bef6fa7d3de/href">https://medium.com/media/6856bc5ba2c51d0d2a8d2bef6fa7d3de/href</a></iframe><p>Open up your project on the browser. You should now see two checkboxes. What happens when you toggle both of these checkboxes? Nothing. If you have the <a href="https://github.com/vuejs/vue-devtools">Vue Devtools</a> installed on your browser you could see that the datasets props on the LineChart component is indeed updated following these two checkboxes. But that won’t trigger the underlying Chart.js to redraw the chart. Let’s fix this!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*G5bZVW6ZE9EaCIQj.gif" /></figure><p>Edit the src/components/LineChart.vue file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7d6835f98c0e49fc93d3b946679f703/href">https://medium.com/media/c7d6835f98c0e49fc93d3b946679f703/href</a></iframe><p>As you may see, we now store the created Chart.js instance within the chart data property. We then simply watch for the datasets props to change.</p><pre>...<br>watch: {<br>  datasets(newDatasets) {<br>    this.chart.data.datasets = newDatasets;<br>    this.chart.update();<br>  }<br>}</pre><p>If the datasets prop is changed. We simply replace the data.datasets property with the new one. We then call the <a href="http://www.chartjs.org/docs/latest/developers/api.html#updateconfig">update()</a> method on the Chart.js instance to re-render the chart with new datasets.</p><p>Now if you try to toggle the checkbox, the chart should be updated accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*fhQpOXUvJtI-q9Xj.gif" /></figure><p>Before the LineChart component instance is destroyed, it’s a good practice to clear up all the object references and all the event listeners attached to the Chart.js instance. We can do so by calling the destroy() method on the Chart.js instance:</p><pre>export default {<br>  name: &#39;monthly-sales-chart&#39;,<br><br>  ...<br><br>  mounted() {<br>    // Omitted...<br>  },<br><br>  beforeDestroy () {<br>    // Don&#39;t forget to destroy the Chart.js instance.<br>    if (this.chart) {<br>      this.chart.destroy()<br>    }<br>  }<br>}</pre><h3>Closing Thought</h3><p>There you have it! A reusable chart component for Vue! You can check out the complete source code on <a href="https://github.com/risan/vue-chart-example">Github</a> and play around with the demo here: <a href="https://risan.github.io/vue-chart-example/">risan.github.io/vue-chart-example</a>.</p><p>Note that on our case we only anticipate changes on the datasets prop. But of course, you might have a case where the labels or even the options are possible to change too. In that case, don’t forget to watch for changes on those props too. Replace the associated chart’s configuration, and call the update() method to re-render the chart.</p><p>There other chart types available on Chart.js, like bar, pie, scatter, and even mixed type. Why don’t you try to abstract away the LineChart component into something that’s even more general; like BaseChart? Which later you can extend to create various chart types.</p><p><em>Originally published at </em><a href="https://risanb.com/code/vue-chart-component-with-chartjs/"><em>r</em>isanb.com</a><em> on October 14, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db85a2d21288" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risan/vue-chart-component-with-chart-js-db85a2d21288">Vue Chart Component with Chart.js</a> was originally published in <a href="https://medium.com/risan">Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building My First iOS Game]]></title>
            <link>https://medium.com/risan/building-my-first-ios-game-394e81512fa6?source=rss----b42a56310d1c---4</link>
            <guid isPermaLink="false">https://medium.com/p/394e81512fa6</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Risan Bagja]]></dc:creator>
            <pubDate>Tue, 16 Oct 2018 20:04:27 GMT</pubDate>
            <atom:updated>2021-09-12T11:58:36.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nrk-Rt1_L64SrRe52Q8f-g.jpeg" /></figure><p>Sunday night two weeks ago, I had nothing better to do. So I started googling for some iOS tutorial and landed on this amazing <a href="https://www.raywenderlich.com/5993-your-first-ios-app">video tutorial</a> by Ray Wenderlich. It’s quite exciting and easy to follow for a total beginner like me. I delved into Swift documentation before and got bored easily. 😝</p><p>On that tutorial, you’ll learn the basic of iOS development by building some simple game named Bull’s Eye. It generates some random number between 1 and 100. It then challenges the user to estimate and move the slider as close as possible to that random number. The closer it gets, the higher the point. It’s pretty simple.</p><p>You can check out the complete project on my Github repository: <a href="https://github.com/risan/bullseye-ios">risan/bullseye-ios</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*IE4iXe0zIxMQvyjf.gif" /><figcaption>Bull’s Eye in Action</figcaption></figure><h3>Variables, Constants, and Data Types</h3><h4>Basic Data Types</h4><p>There are several basic data types provided by Swift, here are some of the types that I’ve used so far:</p><ul><li>Int: For a positive or negative integer number (e.g. 100, 0, or -12);</li><li>Float: For a decimal number (e.g. 3.14 or -0.123);</li><li>Double: Double precision floating point number—a lot more precise than the Float;</li><li>Bool: For boolean value (true or false);</li><li>Character: For a single character (e.g. A, b, or &amp;); and</li><li>String: Collection of a character (e.g. Hello World).</li></ul><h4>Working with Integer</h4><p>Swift also provides several other data types for handling an integer number:</p><ul><li>UInt—the unsigned version of Int (zero and positve number only)</li><li>Int8 and UInt8—the 8 bit version;</li><li>Int16 and UInt16—the 16 bit version;</li><li>Int32 and UInt32—the 32 bit version; and</li><li>Int64 and UInt64—the 64 bit version.</li></ul><p>Unless you know about what you’re doing, always use the Int data type when dealing with an integer number.</p><h4>Working with Decimal</h4><p>There are also several other data types for handling a decimal number:</p><ul><li>Float32—the 32 bit version of floating point type;</li><li>Float64—the 64 bit version; and</li><li>Float80—the extended precision floating point type.</li></ul><p>However, the Swift documentation recommends us to always use the Double data type when dealing with a decimal number.</p><h4>Declaring a Variable</h4><p>Use the var keyword to declare a variable:</p><pre>var name: String = &quot;John Doe&quot;<br>var age: Int = 23<br>var score: Double = 75.34<br>var isAwesome: Bool = true<br>var grade: Character = &quot;A&quot;</pre><p>Since it’s a variable, we are allowed to change the value — as long as it has the same data type.</p><pre>var name: String = &quot;John Doe&quot;<br><br>name = &quot;Foo Bar&quot;<br><br>// Will throw an error, because it&#39;s an integer not a string.<br>name = 12<br><br>// We have to explicitly convert the new value <br>// into the same data type.<br>name = String(12)</pre><h4>Declaring a Constant</h4><p>To declare a constant, we use the let keyword:</p><pre>let max: Int = 100<br>let pi: Double = 3.14<br><br>// Throw an error, since we&#39;re not allowed to change the value.<br>pi = 3.1423</pre><h4>Type Inference</h4><p>Swift is a strongly typed language. However, it allows us to declare a variable or a constant without even specifying its data type. Swift is smart enough to figure out the data type based on its initial value.</p><pre>var totalItems = 5 // Int<br>var totalAmounts = 50.3 // Double<br>let message = &quot;Success!&quot; // String<br>let isPaid = true // Bool<br>let grade = &quot;A&quot; // String</pre><p>Note that by default, a decimal number will be inferred as a Double—not a Float. A round number also will be inferred as an Int, even if the value may also fit in another data type like UInt8.</p><p>In Swift, we can put the value of a variable or a constant within a string like this:</p><pre>&quot;Some string \(yourVariableOrConstant)&quot;</pre><p>When we extrapolate a variable or a constant within a string, we don’t need to explicitly convert the data type — even if it’s not a string.</p><pre>let totalItems = 5<br>let totalAmounts = 50.3<br>let isPaid = true<br>let message = &quot;Success!&quot;<br><br>print(&quot;Total items: \(totalItems)\nTotal amount: $\(totalAmounts)&quot;)<br>print(&quot;Is Paid: \(isPaid)\nMessage: \(message)&quot;)</pre><p>The above code will print the following output:</p><pre>Total items: 5<br>Total amount: $50.3<br>Is Paid: true<br>Message: Success!</pre><p>We can also use the triple quotes (&quot;&quot;&quot;) to construct a multiline string. The following code will have the same exact output like above:</p><pre>print(&quot;&quot;&quot;<br>Total items: \(totalItems)<br>Total amount: $\(totalAmounts)<br>Is Paid: \(isPaid)<br>Message: \(message)<br>&quot;&quot;&quot;)</pre><h3>Functions</h3><p>Use the func keyword to create a function:</p><pre>func sayHello() {<br>    print(&quot;Hello World!&quot;)<br>}<br><br>// Calling the function.<br>sayHello()</pre><h4>Function with Parameter</h4><p>We can also create a function with a parameter:</p><pre>func greet(name: String) {<br>    print(&quot;Hello \(name)!&quot;)<br>}</pre><pre>// Hello Mr Data!<br>greet(name: &quot;Mr Data&quot;)</pre><pre>// Hello Darth Vader!<br>greet(name: &quot;Darth Vader&quot;)</pre><pre>// Throw an error, since we pass a double<br>greet(name: 123.45)</pre><p>Note how we also pass the name when calling the greet function above. In Swift, the name is also called “argument label”.</p><p>We can have as many parameters as we want:</p><pre>func introduce(name: String, age: Int) {<br>    print(&quot;Hi my name is \(name) and I&#39;m \(age) years old.&quot;)<br>}<br><br>introduce(name: &quot;John&quot;, age: 23)<br><br>// Will throw an error, since we can&#39;t change the argument&#39;s order.<br>introduce(age: 19, name: &quot;Luke&quot;)</pre><p>Note that even though the arguments are already labeled, we can’t change the order of these arguments.</p><h4>Omitting Argument Label in a Function</h4><p>We can configure the function so we don’t have to specify the argument label when calling it. To omit the argument label, simply put an underscore (_) before the parameter name:</p><pre>func greet(_ name: String) {<br>    print(&quot;Hi \(name)!&quot;)<br>}<br><br>greet(&quot;Captain Kirk&quot;) // Hi Captain Kirk!<br><br>// Will throw an error, we have to omit the argument label.<br>greet(name: &quot;John&quot;)</pre><p>We can combine a named parameter with the omitted one:</p><pre>func introduce(_ name: String, age: Int) {<br>    print(&quot;Hi my name is \(name) and I&#39;m \(age) years old.&quot;)<br>}</pre><pre>// Hi my name is John and I&#39;m 23 years old.<br>introduce(&quot;John&quot;, age: 23)</pre><p>And of course we can also have multiple parameters without any argument labels:</p><pre>func introduce(_ name: String, _ age: Int) {<br>    print(&quot;Hi my name is \(name) and I&#39;m \(age) years old.&quot;)<br>}</pre><pre>// Hi my name is Jar Jar and I&#39;m 33 years old.<br>introduce(&quot;Jar Jar&quot;, 33)</pre><h4>Renaming the Function Parameter</h4><p>In Swift, we are allowed to have a different identifier between the parameter name and the argument label.</p><pre>func welcome(to name: String) {<br>    print(&quot;Welcome to the \(name)!&quot;)<br>}<br><br>welcome(to: &quot;Jungle&quot;) // Welcome to the Jungle!</pre><p>The to will be used as an argument label when calling the welcome function. While the name will be used as an identifier for the parameter within the function’s body.</p><h4>Function with Return Value</h4><p>So far we’ve only created functions with no return value. To create a function with a return value, simply use the return keyword and declare the return type right before the opening curly brace:</p><pre>func sum(_ a: Int, _ b: Int) -&gt; Int {<br>    return a + b<br>}<br><br>sum(10, 20) // 30<br>sum(10, -20) // -10</pre><h3>Optional</h3><p>“Optional” was one of the concepts that I was struggling with when trying out Swift for the first time years ago. Now I finally understand. It’s simply a data type that accepts nil as a value—which means an absence of value. We use a question mark (?) to indicate an optional type:</p><pre>var name: String? // Optional String type<br>var message: String = &quot;John&quot; // Just regular String type<br><br>name = &quot;John&quot; // We can assign a regular String value<br>name = nil // or we can also assign a `nil`<br><br>// However this will throw an error, since message is not an optional type.<br>message = nil</pre><h4>Optional Binding</h4><p>We can think of optional type as a box. It can either contain something (some value) or nothing at all (a nil value). In order to know what’s inside of this box, we have to open it. In Swift, this process is called “unwrapping”—like unwrapping present box!</p><p>One of the way to “unwrap” an optional type is by using an optional binding. We assign the optional type to some constant using the let keyword; we then wrap this assignment with an if statement like so:</p><pre>var name: String?<br><br>if let unwrappedName = name {<br>    // This block will be executed if name is not nil<br>    print(&quot;Hi \(unwrappedName)!&quot;)<br>} else {<br>    // This block will be executed if name is nil<br>    print(&quot;Name is empty&quot;)<br>}</pre><h3>Class</h3><p>Use the class keyword to define a class:</p><pre>class Person {<br>    let isHuman = true<br>    var name = &quot;John Doe&quot;<br><br>    func sayHi() {<br>        print(&quot;Hi, my name is \(name)!&quot;)<br>    }<br>}<br><br>let john = Person()<br><br>john.isHuman // true<br>john.name // John Doe<br>john.sayHi() // Hi, my name is John Doe!<br><br>john.name = &quot;Yoda&quot;<br>john.sayHi() // Hi, my name is Yoda!<br><br>// Will throw an error because `isHuman` is a constant.<br>john.isHuman = false</pre><p>Just like calling a function, we use Person() to initialize a new object of Person class. We can then use the dot (.) to access the object’s properties and methods.</p><h4>Class Initializer</h4><p>The class can also have an initializer or a constructor. This is a good place for us to set up the class’s instance; like assigning some initial values to the properties:</p><pre>class Person {<br>    var name: String<br>    var age:Int?<br><br>    // The class initializer<br>    init(name: String, age: Int?) {<br>        self.name = name<br>        self.age = age<br>    }<br><br>    func sayHi() {<br>        var message = &quot;Hi, my name is \(name)&quot;<br><br>        if let ageValue = age {<br>            message += &quot; and I&#39;m \(ageValue) years old&quot;<br>        }<br><br>        print(message)<br>    }<br>}<br><br>let anakin = Person(name: &quot;Anakin&quot;, age: 20)<br>let luke = Person(name: &quot;Luke&quot;, age: nil)<br><br>anakin.sayHi() // Hi, my name is Anakin and I&#39;m 20 years old<br>luke.sayHi() // Hi, my name is Luke</pre><p>Note that when the parameter in a method has the same name as one of the class’s property, we can use the self keyword to refer to the class’s property.</p><p>In Swift, we are allowed to declare a function or a method with the same name, as long as it has different parameter signature. And so does the class initializer, we can have several init() with different parameter signature:</p><pre>class Person {<br>    var name: String<br>    var age:Int?<br><br>    // The age parameter is not optional now.<br>    init(name: String, age: Int) {<br>        self.name = name<br>        self.age = age<br>    }<br><br>    // Another init but without age parameter.<br>    init(name: String) {<br>        self.name = name<br>    }<br><br>    func sayHi() {<br>        var message = &quot;Hi, my name is \(name)&quot;<br><br>        if let ageValue = age {<br>            message += &quot; and I&#39;m \(ageValue) years old&quot;<br>        }<br><br>        print(message)<br>    }<br>}<br><br>let anakin = Person(name: &quot;Anakin&quot;, age: 20)<br>let luke = Person(name: &quot;Luke&quot;)<br><br>anakin.sayHi() // Hi, my name is Anakin and I&#39;m 20 years old<br>luke.sayHi() // Hi, my name is Luke</pre><h3>Other Discoveries</h3><p>Here are some other discoveries I’ve made throughout the tutorial:</p><ul><li>We don’t need to use a semicolon (;) at the end of each statement, unless we want to have multiple statements within one line.</li><li>Every UI object dropped to the storyboard from the library, is an object from some class.</li><li>Use the @IBOutlet keyword on the class’s property if we want it to refer to some object on the storyboard.</li><li>Use the @IBAction keyword on the class’s method if want it to be executed when a particular event occurred on some object on the storyboard.</li></ul><h4>Force Unwrapping</h4><pre>@IBOutlet weak var slider: UISlider!</pre><p>The exclamation mark (!) at the end of the above code is used for unwrapping the optional type forcefully. It means that if the slider is nil the code execution will be aborted.</p><h4>Class Inheritance</h4><pre>class ViewController: UIViewController {<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>    }<br>}</pre><p>In the code above, we declare a class named ViewController that inherits from the UIViewController class. In Swift, we are allowed to override the parent’s method. To do so, we have to use the override keyword before the new method declaration. We can also use the super keyword to access parent’s original methods or properties.</p><h4>Known Type Parameter</h4><p>Below is the signature of the setThumbImage method from a UISlider class:</p><pre>func setThumbImage(_ image: UIImage?, for state: UIControl.State)</pre><p>Suppose we have a variable named slider which is an instance of the UISlider class. We can call the above method like this:</p><pre>slider.setThumbImage(someUIImageInstance, for: UIControl.State.normal)</pre><p>UIControl.State is a struct that contains several constants describing the state of a control. And since the type of the for argument is already known to be the UIControl.State, we can actually just use a dot (.) to access the struct’s constant:</p><pre>slider.setThumbImage(someUIImageInstance, for: .normal)</pre><h4>Using a Closure</h4><pre>UIAlertAction(title: &quot;OK&quot;, style: .default, handler: {<br>    action in<br>    self.startNewRound()<br>})</pre><p>The code above is taken from the tutorial’s source code. We declare a closure as an argument for the handler parameter. The in keyword is used to separate the closure’s parameter(s) from the body. In the code above we only have one parameter: action—which is an instance of the newly created UIAlertAction class.</p><h4>Displaying Local HTML File on a WebView</h4><p>Here’s the code that we use to display a locally saved HTML file within the WebKit WebView:</p><pre>// Load the local HTML file named &quot;about.html&quot;<br>if let htmlPath = Bundle.main.path(forResource: &quot;about&quot;, ofType: &quot;html&quot;) {<br>    let htmlUrl = URL(fileURLWithPath: htmlPath)<br>    let htmlUrlRequest = URLRequest(url: htmlUrl)<br>    webView.load(htmlUrlRequest)<br>}</pre><p>Note that the webView identifier above refers to the WKWebView object on the storyboard.</p><h3>Closing Thought</h3><p>I must say, so far I enjoy creating an iOS application using Swift. Swift syntax is cleaner and more concise than its predecessor — Objective C. For me it’s also a lot easier to understand.</p><p>This little quest of mine, leading me to find more tutorials about building iOS development with Swift. So far I’ve done another 4 tutorials:</p><p><a href="https://github.com/risan/autolayout-ios">1. Auto layout practice</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*ERKPqYnS-8WDHsLb.jpg" /></figure><p><a href="https://github.com/risan/stack-views-ios">2. Stack Views practice</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*PixbYm6RjjegDOdz.jpg" /></figure><p><a href="https://github.com/risan/sliding-cards-ios">3. Creating a paginated sliding cards</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*viT9i6MZk1cHXNAH.gif" /></figure><p><a href="https://github.com/risan/war-card-game-ios">4. A War Card Game</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*DLK-mCHXaM_Ax-fo.gif" /></figure><p>I probably should start reading the Swift documentation. 🤔</p><p><em>Originally published at </em><a href="https://risanb.com/code/building-my-first-ios-game/"><em>r</em>isanb.com</a><em> on October 10, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=394e81512fa6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risan/building-my-first-ios-game-394e81512fa6">Building My First iOS Game</a> was originally published in <a href="https://medium.com/risan">Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Set Authorization Header with Apollo Client]]></title>
            <link>https://medium.com/risan/set-authorization-header-with-apollo-client-e934e6517ccf?source=rss----b42a56310d1c---4</link>
            <guid isPermaLink="false">https://medium.com/p/e934e6517ccf</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[apollo]]></category>
            <dc:creator><![CDATA[Risan Bagja]]></dc:creator>
            <pubDate>Tue, 16 Oct 2018 19:50:28 GMT</pubDate>
            <atom:updated>2021-09-12T11:57:59.095Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4J2xFCKxUNcyCRBYJ8RrMw.png" /></figure><p>A GraphQL API often requires us to provide an authorization header to authenticate the request. How can we provide this authorization header using the popular <a href="https://www.apollographql.com/client">Apollo Client</a> library?</p><p>It turns our Apollo already provides us with the <a href="https://www.apollographql.com/docs/link/">apollo-link</a> module. apollo-link is a composable network layer that we can use to configure the HTTP request. With apollo-link, we can create chainable middlewares that will construct our final HTTP request.</p><p>Suppose our initial code to instantiate an Apollo Client look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/823b36112746d41bdae4975bd5ffcfa3/href">https://medium.com/media/823b36112746d41bdae4975bd5ffcfa3/href</a></iframe><p>Let’s say we store our authorization token on a local storage. To set the authorization header, we need to create an instance of ApolloLink and combine it with the current HttpLink instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf5eefdd7fc7d8e348d44040909c452c/href">https://medium.com/media/bf5eefdd7fc7d8e348d44040909c452c/href</a></iframe><p>The ApolloLink accepts exacly one parameter: the “Request Handler” function. This request handler function accepts two parameters: operation and forward. We can use the operation.setContext method to set any HTTP headers. We then call the given forward function to execute the next middleware in chain.</p><p><em>Originally published at </em><a href="https://risanb.com/code/set-authorization-header-with-apollo-client/"><em>r</em>isanb.com</a><em> on April 14, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e934e6517ccf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risan/set-authorization-header-with-apollo-client-e934e6517ccf">Set Authorization Header with Apollo Client</a> was originally published in <a href="https://medium.com/risan">Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Notes from Intro to Machine Learning]]></title>
            <link>https://medium.com/risan/python-notes-from-intro-to-machine-learning-67f2152b90c9?source=rss----b42a56310d1c---4</link>
            <guid isPermaLink="false">https://medium.com/p/67f2152b90c9</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[udacity]]></category>
            <dc:creator><![CDATA[Risan Bagja]]></dc:creator>
            <pubDate>Sat, 28 Apr 2018 20:46:10 GMT</pubDate>
            <atom:updated>2021-09-12T11:56:47.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XiN_WdM1Jr5on6KRTG-1gA.png" /></figure><p>I rarely use Python. I only have one repository at Github that is written in Python: <a href="https://github.com/risan/iris-flower-classifier">iris-flower-classifier</a>. And it was written two years ago!</p><p>A few days ago I took this free course from Udacity: <a href="https://eu.udacity.com/course/intro-to-machine-learning--ud120">Intro to Machine Learning</a>. The machine learning related codes are quite easy to grasp since it simply uses the <a href="http://scikit-learn.org/">scikit-learn</a> modules. But most of the supporting Python modules that are provided by this course were like a black-box to me. I had no idea how to download a file in Python or what’s the difference between a list, a tuple and a dictionary.</p><p>That’s why I decided to read all of the provided Python modules and implement it myself. I ended up refactor most of the code so it’s easier to understand: <a href="https://github.com/risan/intro-to-machine-learning">github.com/risan/intro-to-machine-learning</a>.</p><p>So here are some notes and snippets of Python that I’ve been collecting so far (I’m not even halfway through the course 😝). Also, note that the codes here are still using Python version 2.7.</p><h3>Modules Classes and Functions</h3><h4>Main Entry File</h4><p>Suppose our Python project is stored in /foo/bar directory. And this application has one file that serves as the single entry point. We can name this file __main__.py so we can run this project simply be referencing its directory path:</p><pre># Referencing its directory.<br>$ python /foo/bar<br><br># It&#39;s equivalent to this.<br>$ python /foo/bar/__main__.py</pre><h4>Import Python Module Dynamically</h4><p>Suppose we would like to import a Python module dynamically based on a variable value. We can achieve this through the <a href="https://docs.python.org/2/library/functions.html#__import__">__import__</a> function:</p><pre>module_name = &quot;numpy&quot;<br><br>__import__(module_name)</pre><h4>Multiple Returns in Python</h4><p>In Python, it’s possible for a function or a method to return multiple values. We can do this simply by separating each return value by a comma:</p><pre>def test():<br>    return 100, &quot;foo&quot;<br><br>someNumber, someString = test()</pre><h4>Importing Modules Outside of the Directory</h4><p>In order to import a module from outside of the directory, we need to add that module’s directory path into the current file with sys.path.append. Suppose we have the following directory structure:</p><pre>|--foo<br>| |-- bar.py<br>|<br>|-- tools<br>| |-- speak_yoda.py</pre><p>If we want to use the speak_yoda.py module within the bar.py, we can do the following:</p><pre># /foo/bar.py<br>import os<br><br># Use relative path to tools directory.<br>sys.path.append(&quot;../tools&quot;)<br><br>import speak_yoda</pre><p>However, this won’t work if we run the baz.py file from outside of its foo directory:</p><pre># It works inside of the /foo directory.<br>$ cd /foo<br>$ python bar.py<br><br># But it won&#39;t work if the code runs from outside of /foo directory.<br>$ python foo/bar.py</pre><p>To solve this problem we can refer to the tools directory using its absolute path.</p><pre># /foo/bar.py<br>import os<br>import sys<br><br># Get the directory name for this file.<br>current_dirname = os.path.dirname(os.path.realpath(__file__))<br><br># Use the absolute path to the tools directory<br>tools_path = os.path.abspath(os.path.join(dirname, &quot;../tools&quot;))<br>sys.path.append(tools_path)<br><br>import speak_yoda</pre><h3>Output</h3><h4>Print The Emojis</h4><p>It turns out you can’t just print an emoji or any other Unicode characters to the console. You need to specify the encoding type beforehand:</p><pre># coding: utf8<br><br>print(&quot;😅&quot;)</pre><h4>Pretty Print</h4><p>We can use the pprint module to pretty-print Python data structure with a configurable indentation:</p><pre>import pprint<br>pp = pprint.PrettyPrinter(indent=2)<br><br>pp.pprint(people)</pre><h3>Working with Pathname</h3><p>Read more about pathname manipulations in the <a href="https://docs.python.org/2/library/os.path.html">os.path documentation</a>.</p><h4>Get Filename From URL</h4><p>Suppose the last segment of the URL contains a filename that we would like to download. We can extract this filename with the following code:</p><pre>import os<br>from urlparse import urlparse<br><br>url = &quot;<a href="https://example.com/foo.txt">https://example.com/foo.txt</a>&quot;<br><br>url_components = urlparse(url)<br><br>filename = os.path.basename(url_components.path) # foo.txt</pre><h4>Check if File Exists</h4><p>To check whether the given file path exists or not:</p><pre>import os<br><br>is_exists = os.path.isfile(&quot;foo.txt&quot;)</pre><h4>Create a Directory if It Does Not Exists</h4><p>To create a directory only if it does not exist:</p><pre>import os<br>import errno<br><br>try:<br>    os.makedirs(directory_path)<br>except OSError, e:<br>    if e.errno != errno.EEXIST:<br>        raise</pre><h3>Working with Files</h3><h4>Downloading a File</h4><p>We can use the urllib module to download a file in Python. The first argument is the file URL that we would like to download. The second argument is the optional filename that will be used to store the file.</p><pre>import urllib<br><br>urllib.urlretrieve(&quot;<a href="https://example.com/foo.txt">https://example.com/foo.txt</a>&quot;, &quot;foo.txt&quot;)</pre><p>There’s a built-in tarfile module that we can use to work with Tar file in Python. To extract the tar.gz file we can use the following code:</p><pre>import tarfile<br><br># Open the file.<br>tfile = tarfile.open(&quot;foo.tar.gz&quot;)<br><br># Extract the file to the given path.<br>tfile.extractall(path)</pre><p>We can pass the mode argument to the open method. By default, the mode would be r—reading mode with transparent compression. There are also other mode options that we can use:</p><ul><li>r:gz: Reading mode with gzip compression.</li><li>r:: Reading mode without compression.</li><li>a: Appending mode without compression.</li><li>w: Writting mode without compression.</li><li>Checkout other available options in <a href="https://docs.python.org/2/library/tarfile.html">tarfile documentation</a>.</li></ul><h3>Working with List</h3><h4>Generate a List of Random Numbers</h4><p>Use the for..in syntax to generate a list of random numbers in a one-liner style.</p><pre>import random<br><br># Initialize internal state of random generator.<br>random.seed(42)<br><br># Generate random points.<br>randomNumbers = [random.random() for i in range(0, 10)]<br># [0.6394267984578837, 0.025010755222666936, ...]</pre><h4>Pair Values from Two Lists</h4><p>The built-in zip function can pair values from two lists. However, this zip function will return a list of tuples instead. To get a list of value pairs, we can combine it with for..in syntax:</p><pre>coordinates = [[x, y] for x,y in zip([5,10,15], [0,1,0])]<br># [[5, 0], [10, 1], [15, 0]]</pre><h4>Splitting a List</h4><p>We can easily split a list in Python by specifying the starting index and it’s ending index. Note that the ending index is excluded from the result.</p><p>We can also specify a negative index. And also note that both of these indices are optional!</p><pre>a = [0,1,2,3,4,5]<br><br>a[0:3]  # 0,1,2<br>a[1:3]  # 1,2<br>a[2:]   # 2,3,4,5<br>a[:3]   # 0,1,2<br>a[0:-2] # 0,1,2,3<br>a[-2:]  # 4,5<br>a[:]    # 0,1,2,3,4,5</pre><h4>Filtering a List In One Line</h4><p>We can easily filter a list in Python by combining the for..in and the if syntax together:</p><pre>numbers = range(1,11)<br><br># Filter even numbers only.<br>[numbers[i] for i in range(0, len(numbers)) if numbers[i] % 2 == 0]<br># [2, 4, 6, 8, 10]</pre><h4>Sorting a List in Ascending Order</h4><p>In Python, we can sort a list in ascending order simply by calling the sort method like so:</p><pre>people = [&quot;John&quot;, &quot;Alice&quot;, &quot;Poe&quot;]<br>people.sort()<br>print(people) # [&quot;Alice&quot;, &quot;John&quot;, &quot;Poe&quot;]</pre><h4>Using Filter Function with a List</h4><p>Just like its name, we can use the filter function to filter out our list:</p><pre>numbers = range(1, 11)<br><br>even_numbers = filter(lambda number: number % 2 == 0, numbers)<br># [2, 4, 6, 8, 10]</pre><p>We can break the above statement into two parts:</p><ul><li>lambda number: statement: The first part is the function that we would like to run to every item on the list. number is the variable name we’d like to use in this function to refer to a single item from the numbers list. The following function body must evaluate to truthy/falsy value—falsy means the current item will be removed from the final result.</li><li>numbers: The second parameter is the list that we’d like to filter.</li></ul><h4>Using Reduce with a List of Dictionary</h4><p>We can use the reduce function to calculate the total of a particular key in a list of a dictionary:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c9ddd6226a6872e5919f6589d57e46c/href">https://medium.com/media/3c9ddd6226a6872e5919f6589d57e46c/href</a></iframe><p>It can be broken down into 4 parts:</p><ul><li>lambda total: It’s the variable name that we’d like to use in the function body to refer to the carried or the accumulative value that will finally be returned.</li><li>item: statement: item is the name of the variable we’d like to use within the function body to refer to the single item in the items list. The following function body will be executed in order to define the accumulative value of total for the next iteration.</li><li>items: It’s the list of item that we would like to “reduce”.</li><li>0: The last parameter is optional and it’s the initial accumulative value for the first iteration.</li></ul><p>We can also use this reduce function to find a single item from the list. Here’s an example of code to find the person with the biggest total_payments within the given list of people dictionary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1353e92e6e697cc56547c5ceeb74383/href">https://medium.com/media/d1353e92e6e697cc56547c5ceeb74383/href</a></iframe><h3>Working with Dictionary</h3><h4>Loop Through Dictionary</h4><p>We can use the itervalues method to loop through a dictionary:</p><pre>for person in people.itervalues():<br>    print(person[&quot;email_address&quot;])</pre><p>We can also use the iteritems method if we want to access the key too:</p><pre>for person in people.iteritems():<br>    print(person[0] + &quot;: &quot; + person[1][&quot;email_address&quot;])</pre><h4>Calculate Total of Particular Dictionary Key</h4><p>Suppose we would like to calculate the total amount of salary key on a people dictionary. We can extract the salary key and use the sum function to get the total:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/509e118e3a6828a64b5ea192d690a7b6/href">https://medium.com/media/509e118e3a6828a64b5ea192d690a7b6/href</a></iframe><h3>Working with Numpy</h3><h4>Numpy Create Range of Values with The Given Interval</h4><p>Use the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html">arange</a> method to create an array with an evenly spaced interval.</p><pre>import numpy as np<br><br>np.arange(0, 5, 1)<br># array([0,1,2,3,4])<br><br>np.arange(1, 4, 0.5)<br># array([1. , 1.5, 2. , 2.5, 3. , 3.5])</pre><h4>Numpy Create Coordinate Matrices from Coordinate Vectors</h4><p>We can use the Numpy <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html">meshgrid</a> method to make coordinate matrices from one-dimentional coordinate arrays.</p><pre>import numpy as np<br><br>np.meshgrid([1, 2, 3], [0, 7])<br># [<br>#   array([[1,2,3], [1,2,3]]),<br>#   array([[0,0,0], [7,7,7]])<br># ]</pre><h4>Flatten Numpy Array</h4><p>When we have a multi-dimensional Numpy array, we can easily flatten it with the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html">ravel</a> method:</p><pre>import numpy as np<br><br>arr = np.array([[1,2], [3,4]])<br>arr.ravel()<br># array([1, 2, 3, 4])</pre><h4>Pairing Array Values with Second Axis</h4><p>We can use Numpy c_ function to pair array values with another array that will be it’s second axis. Read the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.c_.html">numpy.c_ documentation</a>.</p><pre>import numpy as np<br><br>x = [1,2]<br>y = [10,20]<br><br>np.c_[x, y]<br># array([1,10], [2,20])</pre><h3>Generate Coordinates Across The Grid</h3><p>With the knowledge of Numpy <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html">arange</a>, <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html">meshgrid</a>, <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html">ravel</a> and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.c_.html">c_</a> methods, we can easily generate an evenly spaced coordinates across the grid so we can pass it to the classifier and plot the decision surface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dbca848cfab5c506d3c238cb6e2f7f9/href">https://medium.com/media/1dbca848cfab5c506d3c238cb6e2f7f9/href</a></iframe><h3>Plotting the Data</h3><h4>Plot The Surface Decision</h4><p>We can pass an evenly spaced coordinates across the grid to the classifier to predict the output on each of that coordinate. We can then use <a href="https://matplotlib.org/api/pyplot_api.html">matplotlib.pyplot</a> to plot the surface decision.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21e7dc8185e50ed3f9c17947945b03ac/href">https://medium.com/media/21e7dc8185e50ed3f9c17947945b03ac/href</a></iframe><p>The classifier output would be a one-dimensional array, so don’t forget to <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html">reshape</a> it back into a two-dimensional array before plotting. The cmap is an optional parameter for the color map. Here we use the seismic color map from pylab module. It has the red-blue colors.</p><h4>Scatter Plot</h4><p>We need to separate the test points based on its predicted label (the speed). So we can plot the test points with two different colors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee45a04c91afa74d91fa9148737170a6/href">https://medium.com/media/ee45a04c91afa74d91fa9148737170a6/href</a></iframe><p>If we want to save the plot into an image, we can use the savefig method instead:</p><pre>plt.savefig(&#39;scatter_plot.png&#39;)</pre><h3>Dealing with Data</h3><h4>Deserializing Python Object</h4><p>We can use <a href="https://docs.python.org/2/library/pickle.html">pickle</a> module for serializing and deserializing Python object. There’s also the cPickle—the faster C implementation. We use both of these modules to deserialize the email text and author list.</p><pre>import pickle<br>import cPickle<br><br># Unpickling or deserializing the texts.<br>texts_file_handler = open(texts_file, &quot;r&quot;)<br>texts = cPickle.load(texts_file_handler)<br>texts_file_handler.close()<br><br># Unpickling or deserializing the authors.<br>authors_file_handler = open(authors_file, &quot;r&quot;)<br>authors = pickle.load(authors_file_handler)<br>authors_file_handler.close()</pre><h4>Split Data for Training and Testing</h4><p>We can use the built-in <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html">train_test_split</a> function from scikit-learn to split the data both for training and testing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e1f4c90968dc61aff2ddc01da883445/href">https://medium.com/media/5e1f4c90968dc61aff2ddc01da883445/href</a></iframe><p>The test_size argument is the proportion of data to split into the test, in our case we split 10% for testing.</p><h4>Vectorized the Strings</h4><p>When working with a text document, we need to vectorize the strings into a list of numbers so it’s easier and more efficient to process. We can use the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html">TfidfVectorizer</a> class to vectorize the strings into a matrix of TF-IDF features.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a0f3e1256dc97ce6106c7d37c8795a7/href">https://medium.com/media/8a0f3e1256dc97ce6106c7d37c8795a7/href</a></iframe><p>Word with a frequency higher than the max_df will be ignored. Stop words are also ignored—stop words are the most common words in a language (e.g. a, the, has).</p><h4>Feature Selection</h4><p>Text can have a lot of features thus it may slow to compute. We can use scikit <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.SelectPercentile.html">SelectPercentile</a> class to select only the important features.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c01cc09b33925abdf85662a399260af/href">https://medium.com/media/7c01cc09b33925abdf85662a399260af/href</a></iframe><p>The percentile is the percentage of features that we’d like to select based on its highest score.</p><p><em>Originally published at </em><a href="https://risanb.com/code/python-notes-from-intro-to-machine-learning/"><em>r</em>isanb.com</a><em> on April 14, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67f2152b90c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risan/python-notes-from-intro-to-machine-learning-67f2152b90c9">Python Notes from Intro to Machine Learning</a> was originally published in <a href="https://medium.com/risan">Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Component with Dot Notation]]></title>
            <link>https://medium.com/risan/react-component-with-dot-notation-7a9853dbf33b?source=rss----b42a56310d1c---4</link>
            <guid isPermaLink="false">https://medium.com/p/7a9853dbf33b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Risan Bagja]]></dc:creator>
            <pubDate>Fri, 13 Apr 2018 20:09:54 GMT</pubDate>
            <atom:updated>2021-09-12T11:56:01.104Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3lZrNA4R5XAAgV5z3nqcg.png" /></figure><p>This is my answer to someone’s question on <a href="https://stackoverflow.com/questions/49256472/react-how-to-extend-a-component-that-has-child-components-and-keep-them/49258038#answer-49258038">StackOverflow</a>. How can we define a React component that is accessible through the dot notation?</p><p>Take a look at the following code. We have the Menu component and its three children Menu.Item:</p><pre>const App = () =&gt; (<br>  &lt;Menu&gt;<br>    &lt;Menu.Item&gt;Home&lt;/Menu.Item&gt;<br>    &lt;Menu.Item&gt;Blog&lt;/Menu.Item&gt;<br>    &lt;Menu.Item&gt;About&lt;/Menu.Item&gt;<br>  &lt;/Menu&gt;<br>);</pre><p>How can we define a component like Menu? Where it has some kind of “sub-component” that is accessible through a dot notation.</p><p>Well, it’s actually a pretty common pattern. And it’s not really a sub-component, it’s just another component being attached to another one.</p><p>Let’s use the above Menu component for example. We’ll put this component to its own dedicated file: menu.js. First, let’s define these two components separately on this module file:</p><pre>// menu.js<br>import React from &#39;react&#39;;<br><br>export const MenuItem = ({ children }) =&gt; &lt;li&gt;{children}&lt;/li&gt;;<br><br>export default const Menu = ({ children }) =&gt; &lt;ul&gt;{children}&lt;/ul&gt;;</pre><p>It’s just a simple functional component. The Menu is the parent with ul tag. And the MenuItem will act as its children. Now we can use these two components like so:</p><pre>import React from &#39;react&#39;;<br>import { render } from &#39;react-dom&#39;;<br>import Menu, { MenuItem } from &#39;./menu&#39;;<br><br>const App = () =&gt; (<br>  &lt;Menu&gt;<br>    &lt;MenuItem&gt;Home&lt;/MenuItem&gt;<br>    &lt;MenuItem&gt;Blog&lt;/MenuItem&gt;<br>    &lt;MenuItem&gt;About&lt;/MenuItem&gt;<br>  &lt;/Menu&gt;<br>);<br><br>render(&lt;App /&gt;, document.getElementById(&#39;root&#39;));</pre><p>Where’s the dot notation? To make our MenuItem component accessible through the dot nation, we can simply attach it to the Menu component as a static property. To do so, we can no longer use the functional component for Menu and switch to the class component instead:</p><pre>// menu.js<br>import React, { Component } from &#39;react&#39;;<br><br>export default const MenuItem = ({ children }) =&gt; &lt;li&gt;{children}&lt;/li&gt;;<br><br>export default class Menu extends Component {<br>  static Item = MenuItem;<br><br>  render() {<br>    return (<br>      &lt;ul&gt;{this.props.children}&lt;/ul&gt;<br>    );<br>  }<br>}</pre><p>Now we can use the dot notation to declare the MenuItem component:</p><pre>import React from &#39;react&#39;;<br>import { render } from &#39;react-dom&#39;;<br>import Menu from &#39;./menu&#39;;<br><br>const App = () =&gt; (<br>  &lt;Menu&gt;<br>    &lt;Menu.Item&gt;Home&lt;/Menu.Item&gt;<br>    &lt;Menu.Item&gt;Blog&lt;/Menu.Item&gt;<br>    &lt;Menu.Item&gt;About&lt;/Menu.Item&gt;<br>  &lt;/Menu&gt;<br>);<br><br>render(&lt;App /&gt;, document.getElementById(&#39;root&#39;));</pre><p>You can also put the MenuItem component definition directly within the Menu class. But this way you can no longer import MenuItem individually.</p><pre>import React, { Component } from &#39;react&#39;;<br><br>export default class Menu extends Component {<br>  static Item = ({ children }) =&gt; &lt;li&gt;{children}&lt;/li&gt;;<br><br>  render() {<br>    return (<br>      &lt;ul&gt;{this.props.children}&lt;/ul&gt;<br>    );<br>  }<br>}</pre><p><em>Originally published at </em><a href="https://risanb.com/code/react-component-with-dot-notation/"><em>r</em>isanb.com</a><em> on April 7, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a9853dbf33b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risan/react-component-with-dot-notation-7a9853dbf33b">React Component with Dot Notation</a> was originally published in <a href="https://medium.com/risan">Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seeding Table with Relationships in Laravel]]></title>
            <link>https://medium.com/risan/seeding-table-with-relationships-in-laravel-c1e18355013f?source=rss----b42a56310d1c---4</link>
            <guid isPermaLink="false">https://medium.com/p/c1e18355013f</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Risan Bagja]]></dc:creator>
            <pubDate>Fri, 13 Apr 2018 20:04:52 GMT</pubDate>
            <atom:updated>2021-09-12T11:53:19.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VrSZ7zyjdruVRKXH5hHLA.jpeg" /></figure><p>This is my answer to someone’s question on <a href="https://stackoverflow.com/questions/49219245/laravel-5-6-how-to-seed-tables-with-relationships-to-other-tables/49219836#answer-49219836">StackOverflow</a>. How can we seed table with relationships in Laravel? Let’s learn how to define relationships on the Eloquent model and use Laravel’s model factory to seed the database.</p><h3>Model and Table Structure</h3><p>Before getting started, let me explain the context of the question. Let’s say we have a Customer model. This model has two relationships to other tables. First, it has a one-to-one relationship with CustomerAddress model—it means a single customer only has one address. The second relationship is one-to-many with CustomerPurchase model—it means a single customer may have multiple purchase records.</p><p>Let’s briefly explore our model schemas.</p><h4>Customer Model</h4><p>The Customer model is a representation of the customers table. It has five columns: id, name, phone, created_at, and updated_at. The migration file might look something like this:</p><pre>// Within the migration file for creating customers table.<br>Schema::create(&#39;customers&#39;, function (Blueprint $table) {<br>    $table-&gt;increments(&#39;id&#39;);<br>    $table-&gt;string(&#39;name&#39;);<br>    $table-&gt;string(&#39;phone&#39;);<br>    $table-&gt;timestamps();<br>});</pre><p>And the model class stored in app/Customer.php looks like this:</p><pre>&lt;?php<br><br>namespace App;<br><br>use Illuminate\Database\Eloquent\Model;<br><br>class Customer extends Model<br>{<br>    protected $fillable = [&#39;name&#39;, &#39;phone&#39;];<br>}</pre><h4>Customer Address Model</h4><p>The CustomerAddress model represents the customer’s address. It uses the customer_addresses table with eight columns on it: id, customer_id, address, city, state, zip, created_at, and updated_at. The migration file looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/889648dec3bdc66ddce7058e5636e7e6/href">https://medium.com/media/889648dec3bdc66ddce7058e5636e7e6/href</a></iframe><p>The model class itself stored in app/CustomerAddress.php and it looks like this:</p><pre>&lt;?php<br><br>namespace App;<br><br>use Illuminate\Database\Eloquent\Model;<br><br>class CustomerAddress extends Model<br>{<br>    protected $fillable = [&#39;address&#39;, &#39;city&#39;, &#39;state&#39;, &#39;zip&#39;];<br>}</pre><h3>Customer Purchase Model</h3><p>Finally, the CustomerPurchase represents the customer_addresses table. It has six columns: id, customer_id, method, amount, created_at, and updated_at. Its migration file looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/828542958350ca04759d005dc432bd0c/href">https://medium.com/media/828542958350ca04759d005dc432bd0c/href</a></iframe><p>The model saved in app/CustomerPurchase.php and it looks like this:</p><pre>&lt;?php<br><br>namespace App;<br><br>use Illuminate\Database\Eloquent\Model;<br><br>class CustomerPurchase extends Model<br>{<br>    const METHOD_CREDIT_CARD = &#39;credit_card&#39;;<br>    const METHOD_PAYPAL = &#39;paypal&#39;;<br><br>    protected $fillable = [&#39;method&#39;, &#39;amount&#39;];<br>}</pre><h3>Defining Relationships</h3><p>Our first step to solve this problem is to define the relationships between these three models. Let’s open our Customer model and define its relationships both with CustomerAddress and CustomerPurchase models.</p><pre>class Customer extends Model<br>{<br>    // Omitted for brevity<br><br>    public function address()<br>    {<br>        return $this-&gt;hasOne(CustomerAddress::class);<br>    }<br><br>    public function purchases()<br>    {<br>        return $this-&gt;hasMany(CustomerPurchase::class);<br>    }<br>}</pre><p>For the one-to-one relationship with CustomerAddress, we use the <a href="https://laravel.com/docs/5.6/eloquent-relationships#one-to-one">hasOne()</a> method. While for the one-to-many relationship with CustomerPurchase we use the <a href="https://laravel.com/docs/5.6/eloquent-relationships#one-to-many">hasMany()</a> method.</p><p>Note that we use singular form for a method name that defines one-to-one relationship: address(). And use the plural form for a method name that defines one-to-many relationship: purchases(). We also omit the customer part, since it’s redundant inside the Customer class. This way, we’ll have a clean and readable API:</p><pre>$customer = App\Customer::find(1);<br><br>$customer-&gt;address;<br><br>$customer-&gt;purchases-&gt;sortBy(&#39;amount&#39;);</pre><h4>Defining Inverse Relationships</h4><p>For this tutorial, it’s not required to define the inverse relationships. But let’s go ahead and define the relationship between CustomerAddress and CustomerPurchase models:</p><pre>class CustomerAddress extends Model<br>{<br>    // Omitted for brevity<br><br>    public function customer()<br>    {<br>        return $this-&gt;belongsTo(Customer::class);<br>    }<br>}</pre><p>We also define the identical customer() method within the CustomerPurchase model:</p><pre>class CustomerPurchase extends Model<br>{<br>    // Omitted for brevity<br><br>    public function customer()<br>    {<br>        return $this-&gt;belongsTo(Customer::class);<br>    }<br>}</pre><h3>The Model Factory</h3><p>Next, we’re going to need to write a model factory for each of our models. We can generate a model factory through artisan command. Open our your terminal and type the following command within your Laravel’s project directory:</p><pre>$ php artisan make:factory CustomerFactory</pre><p>This will create a new file in app\database\factories\CustomerFactory.php. We can have a separate file for each of our model or we can just write all of the model factories code within this single file. Open up the CustomerFactory.php file and define the model factory for our three models:</p><pre>&lt;?php<br><br>use App\Customer;<br>use App\CustomerAddress;<br>use App\CustomerPurchase;<br>use Faker\Generator as Faker;<br><br>$factory-&gt;define(Customer::class, function (Faker $faker) {<br>    return [<br>        &#39;name&#39; =&gt; $faker-&gt;name,<br>        &#39;phone&#39; =&gt; $faker-&gt;phoneNumber,<br>    ];<br>});<br><br>$factory-&gt;define(CustomerAddress::class, function (Faker $faker) {<br>    return [<br>        &#39;address&#39; =&gt; $faker-&gt;streetAddress,<br>        &#39;city&#39; =&gt; $faker-&gt;city,<br>        &#39;state&#39; =&gt; $faker-&gt;stateAbbr,<br>        &#39;zip&#39; =&gt; $faker-&gt;postcode,<br>    ];<br>});<br><br>$factory-&gt;define(CustomerPurchase::class, function (Faker $faker) {<br>    return [<br>        &#39;method&#39; =&gt; $faker-&gt;randomElement([<br>            CustomerPurchase::METHOD_CREDIT_CARD,<br>            CustomerPurchase::METHOD_PAYPAL,<br>        ]),<br>        &#39;amount&#39; =&gt; $faker-&gt;randomFloat(2, 10, 200),<br>    ];<br>});</pre><p>By default, Laravel provides us with <a href="https://github.com/fzaninotto/Faker">Faker</a> library that we can use to generate a random data.</p><p>On model factory for CustomerPurchase, we use randomElement method. It will simply pick a single item from the given array. On our case, we passed the METHOD_CREDIT_CARD and METHOD_PAYPAL constants, so it will randomly return a string either credit_card or paypal.</p><h3>Database Seeding with Model Factory</h3><p>Our model’s relationships are set and the model factories are ready to use. We can now seed our database!</p><p>We can create a separate class for our seeder. But let’s keep it simple and write the code to the database\seeds\DatabaseSeeder.php file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9e8dcec4eb5c812a92def07788f541e/href">https://medium.com/media/f9e8dcec4eb5c812a92def07788f541e/href</a></iframe><p>First, we created 10 customers with random data. Then we loop through the created model’s collection with <a href="https://laravel.com/docs/5.6/collections#method-each">each</a> method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a05df0633c6d948ab5d2aa9c21268fc/href">https://medium.com/media/9a05df0633c6d948ab5d2aa9c21268fc/href</a></iframe><p>For each of the created model instance, we then create one customer address record. We save this one-to-one relationship with the <a href="https://laravel.com/docs/5.6/eloquent-relationships#the-save-method">save()</a> method:</p><pre>$address = factory(App\CustomerAddress::class)-&gt;make();<br>$customer-&gt;address()-&gt;save($address);</pre><p>We also create 5 purchase records for each customer. We then save this one-to-many relationship with saveMany() method:</p><pre>$purchases = factory(App\CustomerPurchase::class, 5)-&gt;make();<br>$customer-&gt;purchases()-&gt;saveMany($purchases);</pre><p>To run the database seeders, run the following artisan command on our terminal:</p><pre>$ php artisan db:seed<br><br># Or if you just want to run a particular seeder class<br>$ php artisan db:seed --class=CustomersTableSeeder</pre><p>And if you want to re-run all of your migration files, you may pass the --seed option to run the seeders.</p><pre>$ php artisan migrate:refresh --seed</pre><p>Our customers, customer_addresses, and customer_purchases should now be filled with random data.</p><p>Further readings:</p><ul><li><a href="https://laravel.com/docs/5.6/eloquent-relationships">Eloquent Relationships</a></li><li><a href="https://laravel.com/docs/5.6/database-testing#relationships">Using Factories with Relationships</a></li></ul><p>Credits:</p><ul><li>Coffee seeds by <a href="https://unsplash.com/@cjoudrey">Christian Joudrey</a> on <a href="https://unsplash.com/photos/aO_jMXTduUE">Unsplash</a>.</li></ul><p><em>Originally published at </em><a href="https://risanb.com/code/seeding-table-with-relationships-in-laravel/"><em>r</em>isanb.com</a><em> on March 18, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1e18355013f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risan/seeding-table-with-relationships-in-laravel-c1e18355013f">Seeding Table with Relationships in Laravel</a> was originally published in <a href="https://medium.com/risan">Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Track User’s Location and Display it on Google Maps]]></title>
            <link>https://medium.com/risan/track-users-location-and-display-it-on-google-maps-41d1f850786e?source=rss----b42a56310d1c---4</link>
            <guid isPermaLink="false">https://medium.com/p/41d1f850786e</guid>
            <category><![CDATA[google-maps]]></category>
            <category><![CDATA[geolocation]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Risan Bagja]]></dc:creator>
            <pubDate>Sat, 07 Apr 2018 23:34:30 GMT</pubDate>
            <atom:updated>2021-09-12T11:54:06.505Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MfzWBqr46CA_R6Vbw0H74A.jpeg" /><figcaption>Globe by <a href="https://unsplash.com/@nicolegeri">Nicole Harrington</a> on <a href="https://unsplash.com/photos/eUyNYtwN0tA">Unsplash</a>.</figcaption></figure><p>This is actually my answer to someone’s question on <a href="https://www.facebook.com/groups/35688476100/">PHP Indonesia</a> Facebook group. How can we track user’s location continuously using the Geolocation API and display it on Google Maps?</p><p>Before getting started, we’re going to need an <a href="https://developers.google.com/maps/documentation/javascript/get-api-key">API Key</a> to use the Google Maps JavaScript API. As a safety measure, don’t forget to set the HTTP referrers on your API key to your own domains.</p><h3>Displaying Google Map on your Page</h3><p>First, let’s start with a simple example: display a map on our HTML page using Google Maps Javascript API.</p><h4>Our HTML Structure</h4><p>Create a new file and put the following HTML structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e8498f07730fe4f22c42ef86f506fa1/href">https://medium.com/media/8e8498f07730fe4f22c42ef86f506fa1/href</a></iframe><p>Safe it as index.html. Don’t worry about the styles.css and script.js, we’ll create these files later.</p><p>The div with the id of map is where we’ll load the map. Also, don’t forget to replace the YOUR_API_KEY part with your own API key from Google.</p><pre>script async defer src=&quot;<a href="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&amp;callback=init">https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&amp;callback=init</a>&quot;&gt;&lt;/script&gt;</pre><p>The optional callback property is where we can define which function to call once the Google Maps JavaScript API is loaded. In our case it’s the init function, we’ll define it later.</p><h4>Add Some Styles</h4><p>Next, let’s add some styles to our HTML page. Create a new CSS file and put the following CSS rules:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39f31aa487db8951f96c6581fcc23e57/href">https://medium.com/media/39f31aa487db8951f96c6581fcc23e57/href</a></iframe><p>Save this file as styles.css. This CSS file simply to make our map’s div occupies the whole screen. We achieve this through <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/flex">flexbox</a>:</p><pre>html {<br>    height: 100%;<br>}<br><br>body {<br>    height: 100%;<br>}<br><br>.container {<br>    display: flex;<br>    flex-direction: column;<br>    height: 100%;<br>}<br><br>.map {<br>    flex: 1;<br>}</pre><h4>Initialize The Map</h4><p>Now, all we have to do is create a new JavaScript file for displaying the map. Type the following codes and save it as script.js.</p><pre>function init() {<br>  new google.maps.Map(document.getElementById(&#39;map&#39;), {<br>    center: { lat: 59.325, lng: 18.069 },<br>    zoom: 15<br>  });<br>}</pre><p>This init() function will be automatically invoked once the Google Maps JavaScript API is loaded. Inside this function we create a new <a href="https://developers.google.com/maps/documentation/javascript/reference/3/#Map">Map</a> instance:</p><pre>new google.maps.Map(element, options);</pre><p>The first parameter is the DOM element where the map will be displayed. In our case, it’s the div with the id of map. The second parameter is our map configuration object. The center property defines the initial coordinate of our map’s center. The zoom property defines the initial zoom level. You can read more about other options in <a href="https://developers.google.com/maps/documentation/javascript/reference/3/#MapOptions">Map Options Documentation</a>.</p><p>Now if we open up our page in the browser, we should see our map is successfully loaded like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OZ-agqEqkTNFtd0-.png" /><figcaption>Our map is loaded!</figcaption></figure><h3>Adding Marker to Your Map</h3><p>Our next step is to learn how to add a marker to our map instance. Open the script.js file and modify it like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a71238a040fb120336f844511c366c1c/href">https://medium.com/media/a71238a040fb120336f844511c366c1c/href</a></iframe><p>Within the init function, we add a new statement that will create an instance of <a href="https://developers.google.com/maps/documentation/javascript/reference/3/#Marker">Marker</a> class.</p><pre>new google.maps.Marker(options);</pre><p>It accepts a single argument: an object of marker’s options. The map property is where the marker will be displayed, that’s why we pass the created Map instance to this property. The position defines the marker’s position. Check out all of the available options in <a href="https://developers.google.com/maps/documentation/javascript/reference/3/#MarkerOptions">Marker Options Documentation</a>.</p><p>We should now see the marker placed on the map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RFeOgrmKS1jezxFQ.png" /><figcaption>Marker on our map.</figcaption></figure><h3>Get User’s Location</h3><p>Our next step would be retrieving user’s location using the JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation">Geolocation API</a>.</p><h4>Using the getCurrentPosition Method</h4><p>Open up our scripts.js file again. Then add the new code section for retrieving user’s location:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fca78b5b608a5e7075ccaa085321a714/href">https://medium.com/media/fca78b5b608a5e7075ccaa085321a714/href</a></iframe><p>The following code checks whether the GeoLocation API is supported by the browser. We simply check if the geolocation property exists within the navigator object.</p><pre>if (&#39;geolocation&#39; in navigator) {<br>    // Geolocation API is supported<br>} else {<br>    // Geolocation API is not supported<br>    alert(&#39;Geolocation is not supported by your browser.&#39;);<br>}</pre><p>If the GeoLocation API is supported, we can then safely use the getCurrentPosition() method to retrieve user’s location.</p><pre>navigator.geolocation.getCurrentPosition(success, error, [options])</pre><p>This method accepts three parameters:</p><ul><li>success: A callback function that will be invoked once the user’s location is retrieved successfully. The callback receives a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Position">Position</a> object that holds the user’s location.</li><li>error: A callback function that will be invoked if user’s location is failed to retrieve. The callback accepts a <a href="https://developer.mozilla.org/en-US/docs/Web/API/PositionError">PositionError</a> object.</li><li>options: Is an optional <a href="https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions">PositionOptions</a> object that can be used to configure the retrieval process.</li></ul><p>Upon successful retrieval, we simply print the user’s coordinate. And if it’s failed, we show the error message using alert.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b80e4f60000c9c21407fb58c2e6f88f7/href">https://medium.com/media/b80e4f60000c9c21407fb58c2e6f88f7/href</a></iframe><p>Open our page in the browser. It will ask your permission to get your current location. Click <strong>Allow</strong> to give it permission and proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ALj8wwOIBS60GXp6.png" /><figcaption>Our page ask for the permission to get the user’s location.</figcaption></figure><blockquote><em>⚠️ Geolocation API is only available in HTTPS</em></blockquote><blockquote><em>Note that this Geolocation API is only available in secure contexts. So you’ll need to access your page through HTTPS protocol.</em></blockquote><p>If it’s successful, you’ll get your location printed on the console similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KpATnnD0jTTlzkTw.png" /><figcaption>Our latitude and longitude printed on the console.</figcaption></figure><h4>Simulating User’s Location on Chrome</h4><p>On Chrome, we can simulate the user’s location. Open up your developer tools. Click on the three-vertical-dots button on the top-right of your developer tools screen. Click on <strong>More tools</strong> » <strong>Sensors</strong> menu. It will bring a new tab named <strong>Sensors</strong> where you can easily override the position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bhGO8XNqHOfgpNqt.png" /><figcaption>The <strong>Sensor</strong> tab on developer tools.</figcaption></figure><p>There’s also some presets for various city locations that we can choose from. Select some cities and reload the page, you should get the city’s location printed on the console.</p><h4>Handling Errors</h4><p>From the Sensors tab, you can also simulate the position unavailable error. From the drop-down select Location unavailable option and reload the page. You’ll get an alert like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iCixTgRRD3sAzK2X.png" /><figcaption>Simulate location unavailable error.</figcaption></figure><p>We only got the error code, but the message property is empty. Apparently, the specification already specifies that this message property is for debugging only and not to be shown directly to the user. That’s why we should rely on the code and provide our own error message instead.</p><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/PositionError/code">PositionError.code</a> may have the following values:</p><ul><li>1: The permission is denied.</li><li>2: The position is unavailable, the Geolocation failed to retrieve the user’s location.</li><li>3: Timeout—when the device does not return the user’s location within the given timeout option.</li></ul><p>Let’s modify our script.js to print out the appropriate error message:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2f3ac20d6c431969775e7af648d26f9/href">https://medium.com/media/b2f3ac20d6c431969775e7af648d26f9/href</a></iframe><p>Now if we select the Location unavailable option from the <strong>Sensors</strong> tab again and reload the page. We should get an alert: Error (2): Position unavailable..</p><h4>Display User’s Location on Google Maps</h4><p>We successfully retrieved user’s location. But our map and marker still displaying the given initial location. Let’s modify our script.js file to properly center the map and marker to user’s location.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48fcaa673c10d529a2f67e5847e1d41e/href">https://medium.com/media/48fcaa673c10d529a2f67e5847e1d41e/href</a></iframe><p>We use the marker’s setPostion() method to change the location of the marker. We pass it an object of the retrieved user’s location.</p><pre>marker.setPosition({<br>  lat: position.coords.latitude,<br>  lng: position.coords.longitude<br>});</pre><p>And we also use the map’s panTo() method to center the map to user’s location:</p><pre>map.panTo({<br>  lat: position.coords.latitude,<br>  lng: position.coords.longitude<br>});</pre><p>Now if we load our page, both the map and marker should show the retrieved user’s location.</p><h4>Let’s Refactor our Code</h4><p>Our code now is getting a bit messy. Let’s refactor it by extracting each step into its own function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec6a80da0aef868770f2a54badce6a74/href">https://medium.com/media/ec6a80da0aef868770f2a54badce6a74/href</a></iframe><p>We use ES2015 object destructuring to easily get access to position.coords.latitude and position.coords.longitude and rename them lat and lng accordingly:</p><pre>onSuccess: ({ coords: { latitude: lat, longitude: lng } }) =&gt; {<br>  //<br>},</pre><p>We also pass an Error object when the Geolocation API is not supported.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c409cfddac2b1af1e9712d34d81493d7/href">https://medium.com/media/c409cfddac2b1af1e9712d34d81493d7/href</a></iframe><h3>Track User’s Location with watchPosition</h3><p>Up until now, we only retrieve user’s location once. How can we track user’s location continuously? By using setInterval()? Well, we can, but it’s not the best solution. To track user’s location continuously, we can use the provided <a href="https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition">watchPostion()</a> method.</p><p>Let’s modify our script.js file to use the watchPosition instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8638ddfe4d98cf268effd4a0a79d6a66/href">https://medium.com/media/8638ddfe4d98cf268effd4a0a79d6a66/href</a></iframe><p>The watchPosition() will be called every time the position of the device changes. This way we can easily track the user’s location.</p><pre>id = navigator.geolocation.watchPosition(success[, error[, options]])</pre><p>The watchPosition() accepts three parameters, it exactly the identical parameters like the one provided for <a href="https://risan.io/track-user-location-google-maps.html#using-the-getcurrentposition-Method">getCurrentPosition()</a>. The only difference is the error callback is optional for the watchPosition().</p><p>It also returns an id like setTimeout() or setInteval() functions. This id can be used to stop tracking user’s location with <a href="https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/clearWatch">clearWatch()</a> method.</p><p>If we reload our page, both the marker and the map position should now be updated every time the location is changed.</p><h4>The PositionOptions</h4><p>Both getCurrentPosition() and watchPosition() accept the optional third parameter. It’s an object of <a href="https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions">PositionOptions</a>. There are three properties that we can configure:</p><ul><li>enableHighAccuracy: It’s a boolean to indicate whether we’d like to get the best possible accuracy or not. Enabling this option may result in slower response time and increase power consumption.</li><li>timeout: It’s a long value in milliseconds that will limit the time for a device to return user’s location. If the device hasn’t returned the location within the specified time, it will throw a timeout error. By default, the value is Infinity which means it will never timeout.</li><li>maximumAge: It’s a long value in milliseconds representing the maximum age of a cached position. By default, it set to 0 and it means that we don’t want the device to use a cached position.</li></ul><p>Let’s configure our trackLocation() function to enable the high accuracy and set a maximum timeout to 5 seconds.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc350056aea3efdbbccef24074f7b228/href">https://medium.com/media/fc350056aea3efdbbccef24074f7b228/href</a></iframe><h4>The Final Touch</h4><p>For the final touch, let’s integrate both the retrieved user’s coordinate and any error message into the UI. Open the index.html file and add a new div for displaying this information:</p><pre>&lt;main class=&quot;container&quot;&gt;<br>    &lt;div id=&quot;map&quot; class=&quot;map&quot;&gt;&lt;/div&gt;<br>    &lt;!-- For displaying user&#39;s coordinate or error message. --&gt;<br>    &lt;div id=&quot;info&quot; class=&quot;info&quot;&gt;&lt;/div&gt;<br>&lt;/main&gt;</pre><p>Now open the styles.css file and add the following rules:</p><pre>.info {<br>    padding: 1rem;<br>    margin: 0;<br>}<br><br>.info.error {<br>    color: #fff;<br>    background: #dc3545;<br>}</pre><p>Finally, let’s update our script.js to print out the coordinate and the error into the #info div.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b31b58eee40990ef54c2e4512da6603e/href">https://medium.com/media/b31b58eee40990ef54c2e4512da6603e/href</a></iframe><p>Now we should get a nice user’s coordinate and error at the bottom of the map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/0*oo_-u20yaCEj-lCf.gif" /></figure><p>You can check out the <a href="https://google-maps-geolocation.bitballoon.com/">live demo</a> and play around with it. You can also get the source for this tutorial on Github: <a href="https://github.com/risan/google-maps-geolocation-example">google-maps-geolocation-example</a>.</p><p>Credits:</p><ul><li>Globe by <a href="https://unsplash.com/@nicolegeri">Nicole Harrington</a> on <a href="https://unsplash.com/photos/eUyNYtwN0tA">Unsplash</a>.</li></ul><p><em>Originally published at </em><a href="https://risanb.com/code/track-user-location-google-maps/"><em>risanb.com</em></a><em> on March 16, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41d1f850786e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risan/track-users-location-and-display-it-on-google-maps-41d1f850786e">Track User’s Location and Display it on Google Maps</a> was originally published in <a href="https://medium.com/risan">Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing SQL Server on macOS]]></title>
            <link>https://medium.com/risan/installing-sql-server-on-macos-9abe76e26414?source=rss----b42a56310d1c---4</link>
            <guid isPermaLink="false">https://medium.com/p/9abe76e26414</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[mssql]]></category>
            <category><![CDATA[macos]]></category>
            <dc:creator><![CDATA[Risan Bagja]]></dc:creator>
            <pubDate>Tue, 13 Feb 2018 14:48:34 GMT</pubDate>
            <atom:updated>2021-09-12T11:51:59.188Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6kZO8kBIc4hQPRYS-Q47nQ.jpeg" /><figcaption>Crates by Frank McKenna on <a href="https://unsplash.com/photos/tjX_sniNzgQ">Unsplash</a></figcaption></figure><p>It’s a bit inconvenience when working on a project that uses the Microsoft SQL Server while your dev machine is either Linux or macOS. I always ended up setting up and using a remote test database.</p><p>But now it’s no longer the case. October last year, SQL Server 2017 for Linux finally went into general availability. It’s container images are also available on <a href="https://hub.docker.com/r/microsoft/mssql-server-linux/">Docker hub</a> for us to use. That means we can finally install SQL Server on macOS!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl3mZdg0qPkLkaW6IM%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fqz-l3mZdg0qPkLkaW6IM&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl3mZdg0qPkLkaW6IM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/87aa4b958712d1926b5d73d0ae9bbe1e/href">https://medium.com/media/87aa4b958712d1926b5d73d0ae9bbe1e/href</a></iframe><h3>Installing Docker</h3><p>First, you’re going to need Docker. If you haven’t had it installed, heads up to the <a href="https://store.docker.com/">Docker store</a> website and download the <a href="https://store.docker.com/editions/community/docker-ce-desktop-mac">community edition for Mac</a>. Just follow the instructions, it’s super easy to install.</p><p>Once it’s installed, you’ll have a new Docker icon on your menu bar. Click this icon and make sure that Docker is already.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*w36bOAApuX7gEKob.png" /></figure><h3>Running SQL Server Container Image</h3><p>Once you have Docker installed and running, open the terminal and run the following command to pull the latest version of SQL Server 2017 container image from Docker hub:</p><pre>$ docker pull microsoft/mssql-server-linux:2017-latest</pre><p>If you want to pull another version, just replace the 2017-latest part with the desired tag. You can check all of the available tags on <a href="https://hub.docker.com/r/microsoft/mssql-server-linux/tags/">Docker hub</a>. For example, if want to pull the GA (General Availability) version instead, use the following command:</p><pre>$ docker pull microsoft/mssql-server-linux:2017-GA</pre><p>Once the image is pulled, you can run it on a new container using the following command:</p><pre>$ docker run -d -p 1433:1433 --name awesome \<br>  -e &#39;ACCEPT_EULA=Y&#39; -e &#39;MSSQL_SA_PASSWORD=P@55word&#39; \<br>  microsoft/mssql-server-linux:2017-latest</pre><ul><li>-d: Detached mode, run the container in the background.</li><li>-p: Publish a container&#39;s port (second value) to the host (first value). In our case, SQL server is listening on port 1433 within the container and we expose it to the same port on the host.</li><li>--name: Assign a name to the container, we named it awesome 😎.</li><li>-e: Set environment variables. ACCEPT_EULA=Y to confirm your acceptance of the <a href="http://go.microsoft.com/fwlink/?LinkId=746388">licensing agreement</a>. MSSQL_SA_PASSWORD=P@55word set the password for the sa user (the default system administrator username). It must be at least 8 characters and contains three of the following categories: lowercase, uppercase, digits, and symbols.</li></ul><p>To list all of the containers, run the following command:</p><pre>$ docker ps -a</pre><p>You should see the output similar to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e6d67a6204eeda75787e38dbeeb132d/href">https://medium.com/media/8e6d67a6204eeda75787e38dbeeb132d/href</a></iframe><p>Locate your awesome container and make sure that its STATUS column is Up. If the status is Exited, checkout the <a href="https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-configure-docker#troubleshooting">troubleshooting guide</a>.</p><h3>Handy Tips &amp; Tools</h3><p>Congratulation! 🎉 You now have Microsoft SQL Server installed on your macOS machine! Here are some common Docker commands that might come in handy for you:</p><pre># Stop the `awesome` container<br>$ docker stop awesome</pre><pre># Start the `awesome` container<br>$ docker start awesome</pre><pre># Forcefully remove the `awesome` container<br>$ docker rm -f awesome</pre><pre># Remove the pulled image<br>$ docker rmi microsoft/mssql-server-linux:2017-latest</pre><p>It’s a bit inconvenience to run the sqlcmd from within the container in order to work with the database. Luckily there are some tools that you can use for interfacing with SQL Server:</p><ul><li><a href="https://tableplus.io/">TablePlus</a>: This is my favorite one. A native macOS application that works not only with MySQL and SQL Server databases but also Postgres and Redis!</li><li><a href="https://docs.microsoft.com/en-us/sql/sql-operations-studio/download">SQL Operations Studio</a>: This one is coming from Microsoft and can be run on Windows, macOS or Linux.</li><li><a href="https://marketplace.visualstudio.com/items?itemName=ms-mssql.mssql#overview">mssql for VS Code</a>: If you’re using <a href="https://code.visualstudio.com/">Visual Studio Code</a>, this extension might come in handy.</li><li><a href="https://www.npmjs.com/package/sql-cli">sql-cli for Node</a>: If you’re a fellow Javascript developer. You can install this sql-cli for Node globally. This way you&#39;ll have the quite similar sqlcmd feel.</li></ul><p><em>Originally published at </em><a href="https://risanb.com/code/installing-sql-server-on-macos/"><em>r</em>isanb.com</a> on 13 February 2018<em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9abe76e26414" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risan/installing-sql-server-on-macos-9abe76e26414">Installing SQL Server on macOS</a> was originally published in <a href="https://medium.com/risan">Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Create My Own Static Site Generator]]></title>
            <link>https://medium.com/risan/i-create-my-own-static-site-generator-fa4bd9981e73?source=rss----b42a56310d1c---4</link>
            <guid isPermaLink="false">https://medium.com/p/fa4bd9981e73</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Risan Bagja]]></dc:creator>
            <pubDate>Sun, 11 Feb 2018 23:30:21 GMT</pubDate>
            <atom:updated>2021-09-12T11:50:32.549Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JSXdBEb340y_cU3vI6up0g.jpeg" /><figcaption>It’s me fooling around — Colorful clown by Levi Saunders on <a href="https://unsplash.com/photos/m_PB-FYlR_Q">Unsplash</a></figcaption></figure><p>Instead of writing a blog post more often, I decided to redesign my four months old blog, ditched Jekyll and built a custom static site generator. The conversation went like this:</p><p><strong>My inner Yoda</strong>: “Write more often this year, you must”</p><p><strong>Dark side of the Force</strong>: “I find the combination of Ruby and Javascript is disturbing”</p><p><strong>Me</strong>: “Okay, let’s reinvent the wheel and build the static site generator entirely in Javascript!”</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl1KugPr0wJONnqhpK%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl1KugPr0wJONnqhpK%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl1KugPr0wJONnqhpK%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="186" frameborder="0" scrolling="no"><a href="https://medium.com/media/571e24504bd63403df8df80eecc3ba94/href">https://medium.com/media/571e24504bd63403df8df80eecc3ba94/href</a></iframe><p>I’m easily seduced by the dark side. It’s my bad habit. Rather than putting more thought into the writing, I procrastinate by rebuilding the blog from the start all over again. I promise myself that this is the last one 🤞. And as a compensation, I tried to make notes on new things I’ve discovered from building this static site generator.</p><p>You can check the code and the content of <a href="https://risanbagja.com/">my blog</a> on my <a href="https://github.com/risan/website">Github repository</a>. It still needs some works to do: add some tests and extracting the generators to its own NPM module.</p><h3>The Tech Stacks</h3><p>Previously I used <a href="https://jekyllrb.com/">Jekyll</a> for generating the website. The thing is, it’s written in Ruby of which I’m not familiar with (it’s just procrastinator talking looking for justification 😛, actually Ruby code is delightfully expressive and readable).</p><p>Although there are some existing static site generators written in Javascript like <a href="https://hexo.io/">Hexo</a> or <a href="https://www.gatsbyjs.org/">Gatsby</a>, I procrastinate by building my own.</p><p>Luckily Javascript has a vibrant community. With its NPM ecosystem, there are tons of ready-to-use Javascript module. It’s like a building block of Lego. Where you can easily pick and plug modules to build your application.</p><p>Although there’s no lego block heavier than a black hole 😛</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/0*N2PRlKBYobKSNvG9.png" /><figcaption>Heaviest objects in the universe. (source: <a href="https://www.reddit.com/r/ProgrammerHumor/comments/6s0wov/heaviest_objects_in_the_universe/">reddit</a>)</figcaption></figure><p>Here are some packages that I use for building this website generator:</p><ul><li><a href="https://github.com/markdown-it/markdown-it">markdown-it</a> for parsing markdown file and convert it into HTML.</li><li><a href="https://highlightjs.org/">highlight.js</a> for syntax highlighting with theme based on Atom’s <a href="https://github.com/atom/one-dark-syntax">one dark</a>.</li><li><a href="https://github.com/jxson/front-matter">front-matter</a> for extracting YAML front matter from the markdown file.</li><li><a href="https://pugjs.org/">pug</a> for templating engine.</li><li><a href="https://webpack.js.org/">webpack</a> for bundling the assets.</li><li><a href="https://github.com/paulmillr/chokidar">chokidar</a> is used in development for watching for changes in markdown files or pug templates.</li></ul><p>I also switch from <a href="https://www.digitalocean.com/">DigitalOcean</a> VPN to the fully managed <a href="https://www.netlify.com/">Netlify</a> service. They offer amazing features like high-availability CDN, automated Git deployment, one-click SSL and best of all: most of them are free!</p><h3>Multiple Webpack Configurations</h3><p>I need two separate output directories for the Webpack build. One is for the non-critical assets in public directory. And the other one is for the critical assets in template directory which later will be injected inline within the generated HTML file. However, in Webpack configuration object, we can only specify one <a href="https://webpack.js.org/concepts/output/">output</a> path.</p><p>Fortunately, Webpack allows us to export multiple configuration objects within the webpack.config.js file. This way we can have two separate build configurations and output paths. Here&#39;s an example:</p><pre>const path = require(&#39;path&#39;);</pre><pre>module.exports = [<br>  {<br>    entry: &#39;./src/assets/scss/critical.scss&#39;,<br>    output: {<br>      path: path.resolve(__dirname, &#39;src/layouts/includes&#39;),<br>      filename: &#39;[name].js&#39;<br>    },<br>    module: {<br>        // ...<br>    }<br>  },<br>  {<br>    entry: &#39;./src/assets/scss/styles.scss&#39;,<br>    output: {<br>      path: path.resolve(__dirname, &#39;public/assets&#39;),<br>      filename: &#39;[name].[hash].js&#39;<br>    },<br>    module: {<br>        // ...<br>    }<br>  }<br>];</pre><h3>Using chokidar as a Watcher</h3><p>I use chokidar for development purpose. It will watch for file changes in blog posts directory (contains the markdown files) and the layouts directory (contains the pug templates). When a file is updated, added or removed, the generator will rebuild the static website. This way I don’t have to manually run the build command every time I make some changes.</p><p>There’s one small issue though. When the chokidar is started for the first time, it repeatedly emits the add event for each file found on the given paths. Causing the build command get executed for multiple times before the file scan is even completed.</p><p>To solve this issue, we can listen for the add event only when the chokidar is finished scanning the given paths. Chokidar will emit the ready event when the initial scan is completed.</p><pre>const chokidar = require(&#39;chokidar&#39;);<br>const watcher = chokidar.watch(&#39;src&#39;);</pre><pre>watcher<br>  .on(&#39;ready&#39;, () =&gt; {<br>    // Listen to `add` event when the initial scan is completed.<br>    watcher.on(&#39;add&#39;, filePath =&gt; {<br>      // Run build command<br>    });<br>  })<br>  .on(&#39;change&#39;, filePath =&gt; {<br>    // Run build command<br>   })<br>  .on(&#39;unlink&#39;, filePath =&gt; {<br>    // Run build command<br>  });</pre><h3>Combining ESLint and Prettier</h3><p>I use both <a href="https://eslint.org/">ESLint</a> and <a href="https://prettier.io/">Prettier</a> together. ESLint for linting the Javascript files and Prettier for automatic code formatting. Besides checking for syntax errors and code quality, ESLint also has its own code formatting rules which can cause a conflict with Prettier.</p><p>To get around this problem we have to disable the conflicting rules in ESLint, let the Prettier do the code formatting. Simply install the <a href="https://github.com/prettier/eslint-config-prettier">eslint-config-prettier</a> package through NPM:</p><pre>$ npm install eslint-config-prettier --save-dev</pre><p>Then update your ESLint configuration file to <a href="https://eslint.org/docs/user-guide/configuring#extending-configuration-files">extend</a> the configuration from the prettier.</p><pre>// .eslintrc.js<br>module.exports = {<br>  extends: [&#39;prettier&#39;]<br>};</pre><h4>One Command to Rule them All</h4><p>It’s inconvenience to have two separate commands to lint and format the javascript files. Fortunately, we can configure the ESLint to run the Prettier for us. So when we run the <a href="https://eslint.org/docs/user-guide/command-line-interface">eslint</a> command, the <a href="https://prettier.io/docs/en/cli.html">prettier</a> command will also get executed.</p><p>First, you need to install the <a href="https://github.com/prettier/eslint-plugin-prettier">eslint-plugin-prettier</a>:</p><pre>$ npm install eslint-plugin-prettier --save-dev</pre><p>Then update your ESLint configuration file like this:</p><pre>// .eslintrc<br>module.exports = {<br>  extends: [&#39;prettier&#39;],<br>  plugins: [&#39;prettier&#39;],<br>  rules: {<br>    &#39;prettier/prettier&#39;: &#39;error&#39;<br>  }<br>};</pre><p>The <a href="https://eslint.org/docs/user-guide/configuring#configuring-plugins">plugins</a> property is for registering an ESLint plugin. While the <a href="https://eslint.org/docs/rules/">rules</a> property is to configure individual ESLint rules, in our case we&#39;ll treat any Prettier formatting issue as an error.</p><p>When you’re using the <a href="https://github.com/prettier/eslint-plugin-prettier">eslint-plugin-prettier</a>, you no longer need to install the <a href="https://github.com/prettier/eslint-config-prettier">eslint-config-prettier</a> package. Since we can get the same configuration from the plugin like so:</p><p>If you want to disable the conflicting ESLint rules and combine both the eslint and prettier commands, you can simplify your configuration by extending the plugin:prettier/recommended. You no longer needs to specify the plugins and rules properties like so:</p><pre>// .eslintrc<br>module.exports = {<br>  extends: [&#39;plugin:prettier/recommended&#39;]<br>};</pre><h3>Built-in promisify Function in Node.js</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl1J9wZJLPywQuKovK%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fstrangerthings-season-1-stranger-things-l1J9wZJLPywQuKovK&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl1J9wZJLPywQuKovK%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e95a00c8f1a9bcdacc93e62ce127e42/href">https://medium.com/media/6e95a00c8f1a9bcdacc93e62ce127e42/href</a></iframe><p>I love using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a>. Compared to the <a href="http://callbackhell.com/">callback</a> style, it’s a lot easier to read and dealt with. I usually use this simple function to convert an asynchronous callback style Javascript function into a function that returns a promise:</p><pre>const fs = require(&#39;fs&#39;);</pre><pre>const promisify = fn =&gt; (...args) =&gt; new Promise((resolve, reject) =&gt;<br>  fn(...args, (err, result) =&gt; (err ? reject(err) : resolve(result)))<br>);</pre><pre>// Promisify the native fs.readFile function.<br>const readFile = promisify(fs.readFile);</pre><pre>// The readFile() will return a promise object.<br>readFile(&#39;death-star-plans.md&#39;, { encoding: &#39;utf8&#39; })<br>  .then(data =&gt; console.log(data))<br>  .catch(err =&gt; console.error(err));</pre><p>Well, it turns out since v8.0.0, Node.js already have a built-in <a href="https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original">promisify</a> function:</p><pre>const fs = require(&#39;fs&#39;);<br>const util = require(&#39;util&#39;);</pre><pre>// Use built-in promisify function.<br>const readFile = util.promisify(fs.readFile);</pre><h3>Immediately Activate The Service Workers</h3><p>I use the <a href="https://developers.google.com/web/fundamentals/primers/service-workers/">Service Workers</a> for the offline support. So when you’ve visited the blog and later you lost your internet connection, you’ll still be able to see an offline version of the homepage.</p><p>It’s tricky to update the service worker code. when the code is updated, it will trigger the <a href="https://developer.mozilla.org/en-US/docs/Web/API/InstallEvent">install event</a>. Even though it’s installed successfully, the updated service worker won’t be activated until the existing service worker is no longer controlling the clients.</p><p>To get around this, we can call the <a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/skipWaiting">self.skipWaiting()</a> method to activate the newly updated service worker immediately. It&#39;s pretty common to call this method within the install event. Though it doesn&#39;t really matter as long as it&#39;s called before or during the waiting period.</p><pre>self.addEventListener(&#39;install&#39;, event =&gt; {<br>  // Installation steps</pre><pre>  self.skipWaiting();<br>});</pre><p>Once it’s activated, the service worker will start taking control on the next page load. If you want to make the service worker takes control immediately, you can call the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Clients/claim">self.clients.claim()</a> method within the activate event:</p><pre>self.addEventListener(&#39;activate&#39;, event =&gt; {<br>  self.clients.claim();<br>});</pre><h3>Closing Thought</h3><p>I’m really happy with my current blog setup. The look and feel are still simple. The performance is also better. It easily scored 100 on almost every <a href="https://developers.google.com/web/tools/lighthouse/">Lighthouse</a> matrix categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2ufekPxhQ8QosVTh.png" /><figcaption>Lighthouse audit result</figcaption></figure><p>Hopefully, I don’t easily seduce by the Dark Side again and put my effort on the writing part instead 🤞. There are also two more things that I haven’t covered here:</p><ol><li>Creating Webpack plugin for removing Javascript build files. Even though your entry point is just an SCSS or a plain CSS file, Webpack will still emit a Javascript build file. I’ve created a plugin for removing this unwanted JS file.</li><li>Creating a <a href="https://github.com/markdown-it/markdown-it">markdown-it</a> plugin to generate an image tag that suits the <a href="https://github.com/aFarkas/lazysizes">lazysizes</a> package. This <a href="https://github.com/aFarkas/lazysizes">lazysizes</a> package is responsible for lazy loading images.</li></ol><p>I’ll write these two topics later on separate blog posts.</p><p><em>Originally published at </em><a href="https://risanb.com/code/i-create-my-own-static-site-generator/"><em>risanb.com</em></a><em> on 11 February 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa4bd9981e73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risan/i-create-my-own-static-site-generator-fa4bd9981e73">I Create My Own Static Site Generator</a> was originally published in <a href="https://medium.com/risan">Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>