<?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"><channel><title><![CDATA[Tomas' Personal Website]]></title><description><![CDATA[Tomas' Personal Website]]></description><link>https://tomasalabes.me</link><generator>RSS for Node</generator><lastBuildDate>Thu, 16 Apr 2026 10:58:57 GMT</lastBuildDate><atom:link href="https://tomasalabes.me/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Useful Webpack DefinePlugin Usages]]></title><description><![CDATA[What the plugin does
The Webpack DefinePlugin allows you to create 
global constants which can be configured at compile time and used in your webpack bundle. 
Example constant definitions:
plugins: [
  //...
  new webpack.DefinePlugin({
      PRODUCT...]]></description><link>https://tomasalabes.me/useful-webpack-defineplugin-usages</link><guid isPermaLink="true">https://tomasalabes.me/useful-webpack-defineplugin-usages</guid><category><![CDATA[webpack]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Tue, 03 Jan 2017 12:30:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723638982492/9dd5b9a0-f2a3-4254-b12d-67cea18b4641.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-the-plugin-does">What the plugin does</h2>
<p>The <a target="_blank" href="https://webpack.github.io/docs/list-of-plugins.html#defineplugin">Webpack DefinePlugin</a> allows you to create 
global constants which can be configured at compile time and used in your webpack bundle. </p>
<p>Example constant definitions:</p>
<pre><code class="lang-javascript">plugins: [
  <span class="hljs-comment">//...</span>
  <span class="hljs-keyword">new</span> webpack.DefinePlugin({
      <span class="hljs-attr">PRODUCTION</span>: <span class="hljs-built_in">JSON</span>.stringify(<span class="hljs-literal">true</span>),
      <span class="hljs-attr">VERSION</span>: <span class="hljs-built_in">JSON</span>.stringify(<span class="hljs-string">"5fa3b9"</span>),
      <span class="hljs-attr">BROWSER_SUPPORTS_HTML5</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">TWO</span>: <span class="hljs-string">"1+1"</span>,
      <span class="hljs-string">"typeof window"</span>: <span class="hljs-built_in">JSON</span>.stringify(<span class="hljs-string">"object"</span>),
      <span class="hljs-attr">env</span>: {
        <span class="hljs-attr">DEVELOPMENT</span>: <span class="hljs-built_in">JSON</span>.stringify(<span class="hljs-literal">false</span>)
      }
  })
  <span class="hljs-comment">//...</span>
]
</code></pre>
<p>These are different ways of setting variables.</p>
<p>When Webpack runs the build, it will replace the exact definitions occurrences 
(<code>PRODUCTION</code>, <code>TWO</code>, <code>typeof window</code>) with the correspondent value (<code>true</code>, <code>"1+1"</code> and <code>"object"</code>).</p>
<p>Let's see some real-world use cases and why this might be useful.</p>
<h2 id="heading-possible-usages">Possible Usages</h2>
<h3 id="heading-client-side-logging">Client-Side Logging</h3>
<p>Server logging is very common and important in all applications. 
<a target="_blank" href="https://www.owasp.org/index.php/Main_Page">OWASP</a> has a very good wiki for what should be included and what shouldn't: 
<a target="_blank" href="https://www.owasp.org/index.php/Logging_Cheat_Sheet">Logging Cheat Sheet</a>. But when it comes to client-side logging, 
it's a bit different.</p>
<p>In the case of web apps, logging is something that you might want during development but avoid in production.</p>
<p>Production client-side logging might:</p>
<ul>
<li>Expose info that you don't want to expose (everything in the client is already "public", 
logging would it make much easier to get...)</li>
<li>Affect your application performance</li>
<li>Trigger an error if trying to be accidentally executed in an old browser without the console object</li>
</ul>
<p>One way to avoid production logging would be setting an env variable for when our build is for development. </p>
<p>Assuming you have different webpack configs for the environments, this is a way of writing the <code>DEVELOPMENT</code> variable:</p>
<p><em>webpack.config.dev.js</em></p>
<pre><code class="lang-javascript">plugins: [
    <span class="hljs-keyword">new</span> webpack.DefinePlugin({
        <span class="hljs-string">'DEVELOPMENT'</span>: <span class="hljs-built_in">JSON</span>.stringify(<span class="hljs-literal">true</span>)
    })
]
</code></pre>
<p>You can also check for the node process env variables with something like</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">new</span> webpack.DefinePlugin({
    <span class="hljs-attr">DEVELOPMENT</span>: <span class="hljs-built_in">JSON</span>.stringify(process.env.NODE_ENV === <span class="hljs-string">'development'</span>)
})
</code></pre>
<p>And then calling webpack like <code>NODE_ENV=development webpack ...</code> 
(I use the configs separation approach).</p>
<p>Later in the code you would reference this variables as such:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> Logger =  {
    <span class="hljs-attr">log</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">msg</span>) </span>{
        <span class="hljs-keyword">if</span>(DEVELOPMENT)    <span class="hljs-built_in">console</span>.log(msg);
    }
    <span class="hljs-comment">// etc</span>
};

Logger.log(<span class="hljs-string">"Hello!"</span>);
</code></pre>
<p>This way, in development this code would be transformed to:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> Logger =  {
    <span class="hljs-attr">log</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">msg</span>) </span>{
        <span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>)    <span class="hljs-built_in">console</span>.log(msg);
    }
};

Logger.log(<span class="hljs-string">"Hello!"</span>);
</code></pre>
<p>and in production to:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> Logger =  {
    <span class="hljs-attr">log</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">msg</span>) </span>{
        <span class="hljs-keyword">if</span>(<span class="hljs-literal">false</span>)    <span class="hljs-built_in">console</span>.log(msg);
    }
};

Logger.log(<span class="hljs-string">"Hello!"</span>);
</code></pre>
<blockquote>
<p>If in production your are using UglifyJS and the <code>dead_code</code> optimization, 
those branches will be removed from the code, because obviously those logs would never be ran.</p>
<p>If you don't care about your console calls <strong>at all</strong>, you can also use UglifyJS <code>drop_console</code> optimization
where it removes all the calls to the console.</p>
<p>Using ESLint? You can add the <code>/* global DEVELOPMENT */</code> comment to ignore the error, or add the <code>globals: { DEVELOPMENT: true }</code> in the <code>.eslintrc</code> file.</p>
</blockquote>
<h3 id="heading-feature-flags">Feature Flags</h3>
<p>You want a feature to not be seen in production, or even not appear in the bundle (again with the UglifyJS optimization on):</p>
<pre><code class="lang-javascript">plugins: [
    <span class="hljs-keyword">new</span> webpack.DefinePlugin({
        <span class="hljs-string">'NICE_FEATURE'</span>: <span class="hljs-built_in">JSON</span>.stringify(<span class="hljs-literal">true</span>),
        <span class="hljs-string">'EXPERIMENTAL_FEATURE'</span>: <span class="hljs-built_in">JSON</span>.stringify(<span class="hljs-literal">false</span>)
    })
]
</code></pre>
<h3 id="heading-services-urls">Services URLs</h3>
<p>During development you want to hit a Service URL to test your app, and in production you want to use the real thing:</p>
<p><em>webpack.config.dev.js</em></p>
<pre><code class="lang-javascript">plugins: [
    <span class="hljs-keyword">new</span> webpack.DefinePlugin({
        <span class="hljs-string">'SERVICE_URL'</span>: <span class="hljs-built_in">JSON</span>.stringify(<span class="hljs-string">"http://mockservice.com"</span>)
    })
]
</code></pre>
<p><em>webpack.config.prod.js</em></p>
<pre><code class="lang-javascript">plugins: [
    <span class="hljs-keyword">new</span> webpack.DefinePlugin({
        <span class="hljs-string">'SERVICE_URL'</span>: <span class="hljs-built_in">JSON</span>.stringify(<span class="hljs-string">"http://realservice.com"</span>)
    })
]
</code></pre>
<p>The same could apply with users or tokens or whatever you use for communicate with services in dev/prod.</p>
<h2 id="heading-environmentplugin">EnvironmentPlugin</h2>
<p>This plugin will allow you to reference environment variables through <code>process.env</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">new</span> webpack.EnvironmentPlugin([
  <span class="hljs-string">"NODE_ENV"</span>
])
</code></pre>
<p>In your code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> env = process.env.NODE_ENV;
</code></pre>
<p>It's a shortcut that allows you to refer to node environment variables using the DefinePlugin internally.
It would be the same than doing:</p>
<pre><code class="lang-javascript">plugins: [
    <span class="hljs-keyword">new</span> webpack.DefinePlugin({
        <span class="hljs-string">'process.env'</span>: {
          <span class="hljs-string">'NODE_ENV'</span>: <span class="hljs-built_in">JSON</span>.stringify(process.env.NODE_ENV)
        }
    })
]
</code></pre>
<p>Do you have more uses of this plugin? I would love to here them in the comments!
See ya</p>
]]></content:encoded></item><item><title><![CDATA[Webpack and the Public Path Config]]></title><description><![CDATA[You have your app bundled with webpack and some resources (like images) that are outside that bundle, and your app can be used in your domain or consumed by someone else in his site.
This post is meant to explain how to manage the url to the resource...]]></description><link>https://tomasalabes.me/webpack-and-the-public-path-config</link><guid isPermaLink="true">https://tomasalabes.me/webpack-and-the-public-path-config</guid><category><![CDATA[webpack]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Sun, 11 Dec 2016 12:30:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723639070310/25251a0f-4bb4-4c98-8e1e-425d486afc75.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You have your app bundled with webpack and some resources (like images) that are outside that bundle, and your app can be used in your domain or consumed by someone else in his site.</p>
<p>This post is meant to explain how to manage the url to the resources that are not part of your webpack bundle, so that it works in your site and in your consumers' sites.</p>
<h2 id="heading-the-case">The Case</h2>
<p>You might have a webpack configuration that uses the <code>url-loader</code> to manage images, possibly with a limit, so that images smaller than X kbs are inlined into the bundle and the rest are requested by webpack dynamically when necessary.</p>
<p>This configuration would be something like this:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// webpack.config.js</span>
<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: <span class="hljs-string">'./main.js'</span>,
    <span class="hljs-attr">output</span>: {
      <span class="hljs-attr">path</span>: <span class="hljs-string">'./build'</span>, <span class="hljs-comment">// This is where images AND js will go</span>
      <span class="hljs-attr">publicPath</span>: <span class="hljs-string">'http://mysite.com/'</span>, <span class="hljs-comment">// This is used to generate URLs to e.g. images</span>
      <span class="hljs-attr">filename</span>: <span class="hljs-string">'bundle.js'</span>,
      <span class="hljs-attr">library</span>: <span class="hljs-string">'myApp'</span>,
      <span class="hljs-attr">libraryTarget</span>: <span class="hljs-string">'umd'</span> <span class="hljs-comment">//loaded via commonjs, amd or globally</span>
  },
  <span class="hljs-attr">module</span>: {
    <span class="hljs-attr">loaders</span>: [
      { <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.(png|jpg)$/</span>, loader: <span class="hljs-string">'url-loader?limit=8192'</span> }, <span class="hljs-comment">// inline base64 URLs for &lt;=8k images, direct URLs for the rest</span>
      { <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.css$/</span>, loader: <span class="hljs-string">'style-loader!css-loader'</span> }, <span class="hljs-comment">// loader for css, imgs will be loaded</span>
      { <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.html$/</span>, loader: <span class="hljs-string">'html-loader'</span> } <span class="hljs-comment">// loader for html, imgs src attrs will be loaded</span>
    ]
  }
};
</code></pre>
<p>And the output of your app would be like:</p>
<pre><code class="lang-kotlin">- ./build/bundle.js
- ./build/myBigImg.jpg
- ./build/myBigImg2.png
</code></pre>
<p>All the images smaller than 8kb are bundled as base64 strings in <code>bundle.js</code>, the rest are requested to <code>output.publicPath</code> + image.</p>
<p>If you see the Network Tab when your bundle is loaded, you might see the requests to:</p>
<ul>
<li><p><code>http://mysite.com/myBigImg.jpg</code></p>
</li>
<li><p><code>http://mysite.com/myBigImg2.png</code></p>
</li>
</ul>
<p>And that's cool! Webpack managed this for us. But...</p>
<p><code>http://myfriendsite.com</code> wants to use my app too, and when he loads my bundle, a request to <code>http://mysite.com/myBigImg.jpg</code> is done! And although it a completely valid request, if I were him, I wouldn't want to rely on <code>mysite.com</code> to have the component working. I would want the images to be requested to my server.</p>
<p>How do I change the <code>publicPath</code> property to point to <code>http://myfriendsite.com</code>?</p>
<p>Here's where the <code>__webpack_publicPath__</code> property comes in, and the good willing of the app author to open the door to customizing the <code>publicPath</code> (or you can always fork it and add it yourself ;) )</p>
<p>This means that the author of the app should have a function to receive the new <code>publicPath</code> as part of its <strong>entry</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// This is the app entry "main.js". I'm using a CommonJS syntax but you can use what you want </span>
<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">load</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">publicPath</span>)</span>{
    <span class="hljs-keyword">if</span>(publicPath) __webpack_publicPath__ = publicPath;
    <span class="hljs-comment">// else the one in the webpack.config.js will be used.</span>

    <span class="hljs-comment">// continue loading the app</span>
  }
}
</code></pre>
<p><strong>It is important that this option is part of the app entry, not any file inside the app.</strong></p>
<p>Like this, the other site can use it like:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> app = <span class="hljs-built_in">require</span>(<span class="hljs-string">'myApp'</span>); <span class="hljs-comment">// output.library config in webpack.config.js</span>
app.load(<span class="hljs-string">'http://myfriendsite.com/'</span>); <span class="hljs-comment">// this can be absolute or relative</span>
<span class="hljs-comment">// do whatever you want with the app</span>
</code></pre>
<p>When loaded, you will see the network requests as:</p>
<ul>
<li><p><code>http://myfriendsite.com/myBigImg.jpg</code></p>
</li>
<li><p><code>http://myfriendsite.com/myBigImg2.png</code></p>
</li>
</ul>
<p>Nice.</p>
<p>Hope it helps, if you know a better or cleaner way please share it in a comment!</p>
<p>Bye!</p>
]]></content:encoded></item><item><title><![CDATA[Working with Webpack and CSS Loaders]]></title><description><![CDATA[As you know, Webpack use Loaders to manage different type of web resources, like css. Being css files so important for web applications, there are more than one way of handling this. There are different loaders and different combination of loaders th...]]></description><link>https://tomasalabes.me/working-with-webpack-and-css-loaders</link><guid isPermaLink="true">https://tomasalabes.me/working-with-webpack-and-css-loaders</guid><category><![CDATA[webpack]]></category><category><![CDATA[css-loader]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Tue, 13 Sep 2016 12:30:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723639144474/9a72dfbf-5486-4311-a8b1-1df2ed244827.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As you know, Webpack use Loaders to manage different type of web resources, like css. Being css files so important for web applications, there are more than one way of handling this. There are different loaders and different combination of loaders that will help you have the right behavior for you app.</p>
<p>We will take a look at these loaders:</p>
<ol>
<li>css-loader</li>
<li>style-loader</li>
<li>style/usable-loader</li>
<li>css-modules</li>
</ol>
<p>And then I will mention some other tools that can help with css development.</p>
<h2 id="heading-css-loaderhttpsgithubcomwebpackcss-loader"><a target="_blank" href="https://github.com/webpack/css-loader">css-loader</a></h2>
<p>This is the plain css loader. <strong>It will return the css code interpreting the resources inside, but it will not add it to the page.</strong></p>
<p>With this loader <code>@import</code> and <code>url(...)</code> are interpreted like <code>require()</code> and will be resolved.
Good loaders for requiring your assets are the <a target="_blank" href="https://github.com/webpack/file-loader">file-loader</a>
and the <a target="_blank" href="https://github.com/webpack/url-loader">url-loader</a> which you should specify in your config.</p>
<p>Then what you do with that css code it's up to you. The next loader will help you with it.</p>
<h2 id="heading-style-loaderhttpsgithubcomwebpackstyle-loader"><a target="_blank" href="https://github.com/webpack/style-loader">style-loader</a></h2>
<p>This loader adds CSS to the DOM by injecting a <code>&lt;style&gt;</code> or <code>&lt;link&gt;</code> tag.</p>
<h3 id="heading-ya"><code>&lt;style&gt;</code></h3>
<p>To inject a <code>&lt;style&gt;</code> you need to get the content of the css file, and then inject that. </p>
<pre><code class="lang-javascript"><span class="hljs-built_in">require</span>(<span class="hljs-string">"style!raw!./file.css"</span>);
<span class="hljs-comment">// =&gt; add rules in file.css to document</span>
</code></pre>
<p>But it's recommended to combine it with the <a target="_blank" href="https://github.com/webpack/css-loader"><code>css-loader</code></a>, as it will interpret all the resources
in your css file, instead of just having the raw css. </p>
<pre><code class="lang-javascript"><span class="hljs-built_in">require</span>(<span class="hljs-string">"style!css!./file.css"</span>);
<span class="hljs-comment">// =&gt; add rules in file.css to document</span>
</code></pre>
<h3 id="heading-yga"><code>&lt;link&gt;</code></h3>
<p>If you want to add a <code>&lt;link&gt;</code> to your css file, you need to first have the url to that file, for that you can use the <a target="_blank" href="https://github.com/webpack/file-loader"><code>file-loader</code></a>. </p>
<pre><code class="lang-javascript"><span class="hljs-built_in">require</span>(<span class="hljs-string">"style/url!file!./file.css"</span>);
<span class="hljs-comment">// =&gt; add a &lt;link rel="stylesheet"&gt; to file.css to document</span>
</code></pre>
<p>Notice that it's not <code>style</code> anymore, but <code>style/url</code>, it's like another flavor of the same loader.</p>
<p>As you can see, these loaders are the ones that help you to add the style to the page.</p>
<h2 id="heading-styleusablehttpsgithubcomwebpackstyle-loaderblobmasterreadmemdreference-counted-api"><a target="_blank" href="https://github.com/webpack/style-loader/blob/master/README.md#reference-counted-api">style/usable</a></h2>
<p>This is another flavor of the style-loader.
With styleable/usable-loader you get the option to inject and remove the styles yourself using a simple API given by the loader.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> myStyle = <span class="hljs-built_in">require</span>(<span class="hljs-string">'myStyle.css'</span>);
myStyle.use(); <span class="hljs-comment">//inject it via a `&lt;style&gt;` element</span>
myStyle.unuse(); <span class="hljs-comment">//removes it</span>
</code></pre>
<p>Something important that you need to know is that these loader works counting references of the css usages (kind of like a GC). So: </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> myStyle = <span class="hljs-built_in">require</span>(<span class="hljs-string">'myStyle.css'</span>);
myStyle.use(); <span class="hljs-comment">//inject it via a `&lt;style&gt;` element (counter = 1)</span>
myStyle.use(); <span class="hljs-comment">//nothing happens, already injected (counter = 2)</span>

myStyle.unuse(); <span class="hljs-comment">// nothing happens! counter should be 0 to remove it (counter = 1)</span>
myStyle.unuse(); <span class="hljs-comment">// removes it (counter = 0)</span>

myStyle.unuse(); <span class="hljs-comment">// nothing happens (counter = -1) -&gt; weird!</span>
</code></pre>
<p>As you can see in the last line, if you call unuse() more than use() you get a negativa counter, which looks weird, I created a <a target="_blank" href="https://github.com/webpack/style-loader/pull/122">PR in github</a> to fix this but the repo seems to be asleep...</p>
<p>A recommended way to use this is having a different suffix for css files that you want to use with this loader, in case you have css files that
you want to load with a <code>&lt;style&gt;</code> and files that you want to load with this API.</p>
<pre><code class="lang-javascript">{
  <span class="hljs-attr">module</span>: {
    <span class="hljs-attr">loaders</span>: [
      { <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.css$/</span>, exclude: <span class="hljs-regexp">/\.useable\.css$/</span>, loader: <span class="hljs-string">"style!css"</span> },
      { <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.useable\.css$/</span>, loader: <span class="hljs-string">"style/useable!css"</span> }
    ]
  }
}
</code></pre>
<h2 id="heading-css-moduleshttpsgithubcomwebpackcss-loadercss-modules"><a target="_blank" href="https://github.com/webpack/css-loader#css-modules">css-modules</a></h2>
<p>This is also a flavor of the <code>css-loader</code>.
This loader helps us the developers to avoid name conflicts while using css, and by doing so, keep our components modular. </p>
<p>When requiring a css file, it will return an object with all the css selectors in that file (if you have images, etc then you first use some of the other loaders). That object should be passed to the html template or react view or whatever, and use the key corresponging to the class you want to use. An example:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.myClass</span> {
    <span class="hljs-attribute">color</span>: red;
}
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> myStyle = <span class="hljs-built_in">require</span>(<span class="hljs-string">'myStyle.css'</span>);
<span class="hljs-comment">// {</span>
<span class="hljs-comment">//     "myClass": "73nsdfsdf7agkfdg73"</span>
<span class="hljs-comment">// }</span>
</code></pre>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"{ { myStyle.myClass } }"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-comment">&lt;!-- would convert to --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"73nsdfsdf7agkfdg73"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>And the final css would be like</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.73nsdfsdf7agkfdg73</span> {
    <span class="hljs-attribute">color</span>: red;
}
</code></pre>
<p>So as you can see, selectors are made universal, avoiding any clash in names and giving more modularity to the components using it. 
It's an interesting approach on an eternal css problem, the global scope. Until <a target="_blank" href="https://www.w3.org/TR/shadow-dom/">Shadow DOM</a> and CSS local scope comes, this might be an option.</p>
<p>More on <code>css-modules</code> <a target="_blank" href="https://github.com/css-modules/css-modules">here</a>.</p>
<h2 id="heading-helpful-tools-and-docs-for-css-development">Helpful tools and docs for css development</h2>
<ul>
<li><a target="_blank" href="https://webpack.github.io/docs/stylesheets.html">Webpack documentation for working with stylesheets</a></li>
<li>Pre-processors loaders<ul>
<li><a target="_blank" href="https://github.com/postcss/postcss-loader">postcss</a></li>
<li><a target="_blank" href="https://github.com/webpack/less-loader">less</a></li>
<li><a target="_blank" href="https://github.com/jtangelder/sass-loader">sass</a></li>
</ul>
</li>
<li>CSS linters<ul>
<li><a target="_blank" href="https://github.com/hyungjs/csslint-loader">csslint loader</a> (plain css linter)</li>
<li><a target="_blank" href="https://github.com/adrianhall/stylelint-loader">stylelint</a> (css linter for pre-processors syntax)</li>
<li><a target="_blank" href="https://github.com/tomasAlabes/stylefmt-loader">stylefmt</a> (fixes common css linters issues automatically)</li>
</ul>
</li>
</ul>
<p>If you are using any of the CSS pre-processors and you want to lint your CSS, you can check <a target="_blank" href="http://tomasalabes.me/blog/_site/web-development/2016/08/26/Webpack-Series-Part-3.html">my post on it</a>.</p>
<p>All these loaders have different configuration options you can check out but I hope this helps you 
to choose what loaders to use and what tools to help you get going!</p>
]]></content:encoded></item><item><title><![CDATA[Webpack + PostCSS + Stylelint + Stylefmt]]></title><description><![CDATA[If you want to, with Webpack you can use different pre-processors for your CSS: Sass, Less and PostCSS are the most popular ones. I won't go into the differences between them but I will say why I chose PostCSS. 
I like how extensible is via its plugi...]]></description><link>https://tomasalabes.me/webpack-postcss-stylelint-stylefmt</link><guid isPermaLink="true">https://tomasalabes.me/webpack-postcss-stylelint-stylefmt</guid><category><![CDATA[webpack]]></category><category><![CDATA[PostCSS]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Fri, 26 Aug 2016 12:30:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723639167281/224ae81b-7caf-4ac2-bbcf-3703002fe74d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you want to, with Webpack you can use different pre-processors for your CSS: Sass, Less and PostCSS are the most popular ones. I won't go into the differences between them but I will say why I chose PostCSS. </p>
<p>I like how extensible is via its plugins, gives me the freedom to pick and choose, and why not extend it myself. The rest is like a canned product, leave it or take it, it works but I find PostCSS extensibility better.</p>
<h1 id="heading-postcss">PostCSS</h1>
<p>The configuration to use PostCSS is the following:</p>
<p>First install the <a target="_blank" href="https://github.com/postcss/postcss-loader">postcss-loader</a>, we are going to let webpack handle the processing while bundling.</p>
<pre><code class="lang-bash">npm install postcss-loader --save-dev
</code></pre>
<p>Then add it to your <code>webpack.config.js</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">module</span>.exports = {
    <span class="hljs-attr">module</span>: {
        <span class="hljs-attr">loaders</span>: [
            {
                <span class="hljs-attr">test</span>:   <span class="hljs-regexp">/\.css$/</span>,
                loader: <span class="hljs-string">"style-loader!css-loader!postcss-loader"</span>
            }
        ]
    },
    <span class="hljs-attr">postcss</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> [];
    }
}
</code></pre>
<p>This won't do anything until we use a plugin, the one that gives you the "Sass/Less" most common features is <a target="_blank" href="https://github.com/jonathantneal/precss">precss</a>.</p>
<pre><code class="lang-bash">npm install precss --save-dev
</code></pre>
<p>Then we use it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> precss = <span class="hljs-built_in">require</span>(<span class="hljs-string">'precss'</span>);

<span class="hljs-built_in">module</span>.exports = {
    <span class="hljs-attr">module</span>: {
        <span class="hljs-attr">loaders</span>: [
            {
                <span class="hljs-attr">test</span>:   <span class="hljs-regexp">/\.css$/</span>,
                loader: <span class="hljs-string">"style-loader!css-loader!postcss-loader"</span>
            }
        ]
    },
    <span class="hljs-attr">postcss</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> [precss];
    }
}
</code></pre>
<p>And now you can write with the <code>precss</code> syntax in your css!</p>
<h1 id="heading-stylelint">Stylelint</h1>
<p>Besides helping with standarizing quality, I always think that a great way to learn a languague/framework/technology is leaning on tools that "already know" what are the good practices that you need to follow. In case of PostCSS this is <a target="_blank" href="https://github.com/stylelint/stylelint">Stylelint</a>. It's a CSS linter that helps you enforce consistent conventions and avoid errors in your stylesheets. It works for the 3 pre-processors we mentioned.</p>
<p>The best option out there integrated with Webpack right now I think is the <a target="_blank" href="https://github.com/vieron/stylelint-webpack-plugin">stylelint-webpack-plugin</a>. You can always use the CLI interface too.</p>
<p>Let's see how to configure it:</p>
<pre><code class="lang-bash">npm install --save stylelint-webpack-plugin
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> StyleLintPlugin = <span class="hljs-built_in">require</span>(<span class="hljs-string">'stylelint-webpack-plugin'</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-comment">// ...</span>
  <span class="hljs-attr">plugins</span>: [
    <span class="hljs-keyword">new</span> StyleLintPlugin({<span class="hljs-comment">/* Options */</span>}),
  ],
  <span class="hljs-comment">// ...</span>
}
</code></pre>
<p>All the options for it can be seen <a target="_blank" href="https://github.com/vieron/stylelint-webpack-plugin#options">here</a>. This will output all the corresponding warnings/erros and fail if you want it to. Just one note there, the options example says:</p>
<pre><code class="lang-javascript">context: <span class="hljs-string">'inherits from webpack'</span>
</code></pre>
<p><em>"inherits from webpack"</em> is not a valid value, I've seen people defining it like that, but it's not a valid value (see <a target="_blank" href="https://github.com/vieron/stylelint-webpack-plugin/issues/7">this issue</a>).</p>
<h1 id="heading-stylefmt">Stylefmt</h1>
<p>When using linters you also might need something that helps you fixing the low-hanging fruit problems in your stylesheets. This is key when you are introducing a linter into an existing project. <a target="_blank" href="https://github.com/morishitter/stylefmt">stylefmt</a> aims to help with that.</p>
<p>Right now, with Webpack, you can use the <a target="_blank" href="https://github.com/tomasAlabes/stylefmt-loader">stylefmt-loader</a>. Same as Stylelint, the CLI is also available.</p>
<p>This loader will automatically fix whatever it can in your stylesheets before pre-processing them.</p>
<p>The configuration:</p>
<pre><code class="lang-bash">npm install --save stylefmt-loader
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-string">"module"</span>: {
    <span class="hljs-string">"loaders"</span>: [
        {<span class="hljs-string">"test"</span>: <span class="hljs-regexp">/\.css/</span>, <span class="hljs-string">"loader"</span>: <span class="hljs-string">"css!postcss!stylefmt"</span>}
        ]
    }
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>With this tools, you have the power to scale your css development in your project, with a set of standards and rules that will be automatically enforced in your dev process, making your application easier to maintain and improving the overall quality of it.</p>
<p>Hope it helps!</p>
<p>Till next time!</p>
]]></content:encoded></item><item><title><![CDATA[Webpack (AMD) + Karma + Mocha]]></title><description><![CDATA[Here's the situation:

You bundle your app/library with output.libraryTarget = amd (and for the sake of the example let's say that also output.library = "myLibrary")
You want to test it using Mocha
You want to run your tests using Karma

I had a few ...]]></description><link>https://tomasalabes.me/webpack-amd-karma-mocha</link><guid isPermaLink="true">https://tomasalabes.me/webpack-amd-karma-mocha</guid><category><![CDATA[webpack]]></category><category><![CDATA[karma]]></category><category><![CDATA[mocha]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Sun, 01 May 2016 12:30:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723639214123/a0c72128-9eb7-4c42-9bb6-6e13cc9e3686.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Here's the situation:</p>
<ul>
<li>You bundle your app/library with <code>output.libraryTarget = amd</code> (and for the sake of the example let's say that also <code>output.library = "myLibrary"</code>)</li>
<li>You want to test it using Mocha</li>
<li>You want to run your tests using Karma</li>
</ul>
<p>I had a few challengues here and I haven't found any documentation about it so I thought this might be useful to somebody.</p>
<p>You have to use:</p>
<ul>
<li><a target="_blank" href="https://github.com/karma-runner/karma-mocha">karma-mocha</a> to run your mocha tests with karma. You can also use whatever test framework they support</li>
<li><a target="_blank" href="https://github.com/karma-runner/karma-requirejs">karma-requirejs</a> to load your amd app, this is <strong>key</strong>, we'll see why.</li>
</ul>
<p>First, the obvious:</p>
<pre><code class="lang-bash">npm i -D karma-mocha karma-requirejs
</code></pre>
<p>You might need to install other peer dependencies like <code>requirejs</code> and <code>mocha</code>.</p>
<p>In your <code>karma.conf.js</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">config</span>) </span>{
    config.set({

        <span class="hljs-comment">// add the installed frameworks here</span>
        <span class="hljs-attr">frameworks</span>: [<span class="hljs-string">"mocha"</span>, <span class="hljs-string">"requirejs"</span>],

        <span class="hljs-attr">files</span>: [
            <span class="hljs-comment">//here we include all tests, see the file below</span>
            <span class="hljs-string">"src/test/index.js"</span>,
            <span class="hljs-comment">//this is the file that will require our amd bundle, see the file below</span>
            <span class="hljs-string">"src/test/runner.js"</span>,
        ],

        <span class="hljs-attr">preprocessors</span>: [
            <span class="hljs-comment">// preprocess all your tests with webpack, so you bundle all the necessary dependencies</span>
            <span class="hljs-string">"src/test/index.js"</span> : [<span class="hljs-string">"webpack"</span>]
        ],

        <span class="hljs-comment">// load plugins</span>
        <span class="hljs-attr">plugins</span>: [
            <span class="hljs-built_in">require</span>(<span class="hljs-string">"karma-mocha"</span>),
            <span class="hljs-built_in">require</span>(<span class="hljs-string">"karma-requirejs"</span>)
        ]
    });
};
</code></pre>
<p>Karma will load (you can see all this if you run the tests with a browser, in the <code>debug.html</code>)</p>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- ... --&gt;</span>
<span class="hljs-comment">&lt;!-- Dynamically replaced with &lt;script&gt; tags --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/base/node_modules/requirejs/require.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/base/node_modules/karma-requirejs/lib/adapter.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/css"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/base/node_modules/mocha/mocha.css"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/base/node_modules/mocha/mocha.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/base/node_modules/karma-mocha/lib/adapter.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/base/src/test/js/index.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/base/src/test/js/runner.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span>&gt;</span><span class="javascript">
  <span class="hljs-built_in">window</span>.__karma__.loaded();
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-comment">&lt;!-- ... --&gt;</span>
</code></pre>
<ol>
<li>The karma runner code</li>
<li><code>requirejs</code> and <code>requirejs-adapter</code>.</li>
<li><code>mocha</code> and <code>mocha-adapter</code></li>
<li>Your <code>index.js</code> bundle (as you defined your <code>libraryTarget: amd</code> it will just define your module)</li>
<li>And your <code>runner.js</code> that will require your <code>myLibrary</code> module.</li>
<li>The script that starts the tests, enclosed in a script tag.</li>
</ol>
<p>It's important that you use <code>karma-requirejs</code> instead of just <code>requirejs</code> from your <code>bower_components</code> or <code>node_modules</code>, because what you really need is the <code>requirejs-adapter</code>, why? </p>
<p>As the execution of your tests is asynchronous, the call to <code>window.__karma__.loaded()</code> would be done <strong>before</strong> executing the tests. The <code>requirejs-adapter</code> overrides the <code>__karma__.loaded</code> function to do nothing and waits for <strong>your</strong> call to <code>window.__karma__.start()</code> (karma's "loaded()" calls "start()").</p>
<p>Hence:</p>
<p><strong>index.js</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// require all modules ending in "_test" from the</span>
<span class="hljs-comment">// current directory and all subdirectories</span>
<span class="hljs-keyword">var</span> testsContext = <span class="hljs-built_in">require</span>.context(<span class="hljs-string">"."</span>, <span class="hljs-literal">true</span>, <span class="hljs-regexp">/_test$/</span>);
testsContext.keys().forEach(testsContext);
</code></pre>
<p>So the runner needs to load your amd library and tell karma to start running the tests!</p>
<p><strong>runner.js</strong></p>
<pre><code class="lang-javascript"><span class="hljs-built_in">require</span>([<span class="hljs-string">"myLibrary"</span>], <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">myLibrary</span>)</span>{
    <span class="hljs-comment">// probably you don't want to do anything with your library here</span>
    <span class="hljs-comment">// I didn't...</span>

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Let the tests begin..."</span>);

    <span class="hljs-comment">// now that our bundle with the tests are loaded, run the tests!</span>
    <span class="hljs-built_in">window</span>.__karma__.start();

});
</code></pre>
<p>This way, your app + tests are loaded and required, and your tests can be ran by karma.</p>
<p>I figured all these out by using these resources:</p>
<ul>
<li>https://karma-runner.github.io/0.13/plus/requirejs.html</li>
<li>https://github.com/karma-runner/karma-requirejs</li>
<li>https://github.com/kjbekkelund/karma-requirejs</li>
</ul>
<p>Hope it helps!
Till the next one.</p>
]]></content:encoded></item><item><title><![CDATA[(Some) Webpack Configuration Options Explained]]></title><description><![CDATA[I've been migrating a big project that used requirejs optimizer to bundle all the javascript modules to Webpack. As everybody knows Webpack's documentation is not the best but the community has helped writing about their experiences and doing tutoria...]]></description><link>https://tomasalabes.me/some-webpack-configuration-options-explained</link><guid isPermaLink="true">https://tomasalabes.me/some-webpack-configuration-options-explained</guid><category><![CDATA[webpack]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Sat, 30 Apr 2016 12:30:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723639237274/a7c6b805-3019-443b-933c-b80d97507966.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I've been migrating a big project that used requirejs optimizer to bundle all the javascript modules to Webpack. As everybody knows Webpack's documentation is not the best but the community has helped writing about their experiences and doing tutorials about it.</p>
<p>To do my part I would like to write a series sharing my experiences during my migration.</p>
<p>I'll start with Webpack's <a target="_blank" href="https://webpack.github.io/docs/configuration.html">configuration</a>, trying to explain some properties and give more info of what's not in the official docs, with some examples.</p>
<h2 id="heading-modulenoparse">module.noParse</h2>
<p>This property can be either a RegEx or an array of RegExs. All matching files will not be parsed by webpack.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">module</span>.exports = {
    <span class="hljs-comment">//...    </span>
    <span class="hljs-attr">module</span>: {
        <span class="hljs-attr">noParse</span>: [ <span class="hljs-regexp">/^dontParseThis$/</span> ]
    }
    <span class="hljs-comment">//...</span>
}
</code></pre>
<p>This means that webpack, when requiring them, will bundle them <code>as is</code>, without doing anything to them. This means that:</p>
<ol>
<li>These files can only have require calls to dependencies marked as external or any dependency that isn't in any webpack chunk. Because that dependency will be "encapsulated" by webpack inside the bundle and won't be accesible through regular <code>require</code> calls.</li>
<li>You can skip big files that are already optimized, increasing the speed of the build.</li>
<li>Although they are not parsed by webpack, they will be part of your bundle.</li>
</ol>
<h2 id="heading-outputlibrarytarget">output.libraryTarget</h2>
<p>You developed your <code>magicLibrary</code> in a very modular fashion using all the power of webpack. But have you thought how your users are going to consume it? Here's where <code>libraryTarget</code> config comes in.</p>
<p><em>First a quick note, to give your library a name (you should), set the <code>output.library</code> config to it.</em></p>
<p>For the distribution type you have several options:</p>
<h4 id="heading-var-default">var (default)</h4>
<p>When your library is loaded, the <strong>return value of your entry point</strong> will be assigned to a variable:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> magicLibrary = _entry_return_;
<span class="hljs-comment">// your users will use your library like:</span>
magicLibrary.doTheTrick();
</code></pre>
<p><em>(Not specifying a <code>output.library</code> will cancel this <code>var</code> configuration)</em></p>
<h4 id="heading-this">this</h4>
<p>When your library is loaded, the <strong>return value of your entry point</strong> will be assigned to <code>this</code>, the meaning of <code>this</code> is up to you:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">this</span>[<span class="hljs-string">"magicLibrary"</span>] = _entry_return_;
<span class="hljs-comment">// your users will use your library like:</span>
<span class="hljs-built_in">this</span>.magicLibrary.doTheTrick();
magicLibrary.doTheTrick(); <span class="hljs-comment">//if this is window</span>
</code></pre>
<p><code>this</code> will depend mostly on how you are injecting the bundle.</p>
<h4 id="heading-commonjs">commonjs</h4>
<p>When your library is loaded, the <strong>return value of your entry point</strong> will be part of the <code>exports</code> object. As the name implies, this is used in commonjs environments.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">exports</span>[<span class="hljs-string">"magicLibrary"</span>] = _entry_return_;
<span class="hljs-comment">//your users will use your library like:</span>
<span class="hljs-built_in">require</span>(<span class="hljs-string">"magicLibrary"</span>).doTheTrick();
</code></pre>
<h4 id="heading-commonjs2">commonjs2</h4>
<p>When your library is loaded, the <strong>return value of your entry point</strong> will be part of the <code>exports</code> object. As the name implies, this is used in commonjs environments.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">module</span>.exports = _entry_return_;
<span class="hljs-comment">//your users will use your library like:</span>
<span class="hljs-built_in">require</span>(<span class="hljs-string">"magicLibrary"</span>).doTheTrick();
</code></pre>
<p><em>Wondering the difference between commonjs and commonjs2? Check <a target="_blank" href="https://github.com/webpack/webpack/issues/1114">this</a> out. (They are pretty much the same)</em></p>
<h4 id="heading-amd-asynchronous-module-definition">amd <em>(Asynchronous Module Definition)</em></h4>
<p>In this case webpack will surround you library with an AMD.</p>
<p>But there is a <strong>very important pre-requisite, your entry chunk must be defined with the <code>define</code> property</strong>, if not, webpack wil create the AMD module, but without dependencies. I learned this the hard way, it's logical but not obvious I think. Anyway... the output will be something like this:</p>
<pre><code class="lang-javascript">define([], <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">//what this module returns is what your entry chunk returns</span>
});
</code></pre>
<p>But if you download this script, first you may get a <code>error: define is not defined</code>, it's ok! if you are distributing your library as with amd, then your users need to use require to load it.
But, <code>require([_what_])</code>? </p>
<p><code>output.library</code>!</p>
<pre><code class="lang-javascript">output: {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"magicLibrary"</span>,
    <span class="hljs-attr">libraryTarget</span>: <span class="hljs-string">"amd"</span>
}
</code></pre>
<p>And the module will be:</p>
<pre><code class="lang-javascript">define(<span class="hljs-string">"magicLibrary"</span>, [], <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">//what this module returns is what your entry chunk returns</span>
});

<span class="hljs-comment">// And then your users will be able to do:</span>
<span class="hljs-built_in">require</span>([<span class="hljs-string">"magicLibrary"</span>], <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">magic</span>)</span>{
    magic.doTheTrick();
});
</code></pre>
<h4 id="heading-umd-universal-module-definition">umd <em>(Universal Module Definition)</em></h4>
<p>This is a way for your library to work with all module definitions (and where aren't modules at all). It will work with commonjs, amd and as global variable.</p>
<p>Here to name your module you need the another property:</p>
<pre><code class="lang-javascript">output: {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"magicLibrary"</span>,
    <span class="hljs-attr">libraryTarget</span>: <span class="hljs-string">"umd"</span>,
    <span class="hljs-attr">umdNamedDefine</span>: <span class="hljs-literal">true</span>
}
</code></pre>
<p>And finally the output is:</p>
<pre><code class="lang-javascript">(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">webpackUniversalModuleDefinition</span>(<span class="hljs-params">root, factory</span>) </span>{
    <span class="hljs-keyword">if</span>(<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">exports</span> === <span class="hljs-string">'object'</span> &amp;&amp; <span class="hljs-keyword">typeof</span> <span class="hljs-built_in">module</span> === <span class="hljs-string">'object'</span>)
        <span class="hljs-built_in">module</span>.exports = factory();
    <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(<span class="hljs-keyword">typeof</span> define === <span class="hljs-string">'function'</span> &amp;&amp; define.amd)
        define(<span class="hljs-string">"magicLibrary"</span>, [], factory);
    <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">exports</span> === <span class="hljs-string">'object'</span>)
        <span class="hljs-built_in">exports</span>[<span class="hljs-string">"magicLibrary"</span>] = factory();
    <span class="hljs-keyword">else</span>
        root[<span class="hljs-string">"magicLibrary"</span>] = factory();
})(<span class="hljs-built_in">this</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">//what this module returns is what your entry chunk returns</span>
});
</code></pre>
<p>Module proof library.</p>
<h2 id="heading-externals">externals</h2>
<p>Externals can be tricky, specially with all the ways you have for defining them and the combination with the <code>output.libraryTarget</code> configuration.
These dependencies won't be resolved by webpack, but should become dependencies of the resulting bundle. The kind of the dependency depends on <code>output.libraryTarget</code>.</p>
<p>I'll paste the official documentation that I think is complete and add comments.</p>
<pre><code class="lang-javascript">externals: [
    {
        <span class="hljs-attr">a</span>: <span class="hljs-literal">false</span>, <span class="hljs-comment">// a is not external</span>
        <span class="hljs-attr">b</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// b is external (require("b"))</span>
        <span class="hljs-string">"./c"</span>: <span class="hljs-string">"c"</span>, <span class="hljs-comment">// "./c" is external (require("c"))</span>
        <span class="hljs-string">"./d"</span>: <span class="hljs-string">"var d"</span> <span class="hljs-comment">// "./d" is external (d)</span>
    },
    <span class="hljs-comment">// Every non-relative module is external</span>
    <span class="hljs-comment">// abc -&gt; require("abc")</span>
    <span class="hljs-regexp">/^[a-z\-0-9]+$/</span>,
    <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">context, request, callback</span>) </span>{
        <span class="hljs-comment">// Every module prefixed with "global-" becomes external</span>
        <span class="hljs-comment">// "global-abc" -&gt; abc</span>
        <span class="hljs-keyword">if</span>(<span class="hljs-regexp">/^global-/</span>.test(request))
            <span class="hljs-keyword">return</span> callback(<span class="hljs-literal">null</span>, <span class="hljs-string">"var "</span> + request.substr(<span class="hljs-number">7</span>));
        callback();
    },
    <span class="hljs-string">"./e"</span> <span class="hljs-comment">// "./e" is external (require("./e"))</span>
]
</code></pre>
<table>
<thead>
<tr>
<th>type</th>
<th>value</th>
<th>resulting import code</th>
</tr>
</thead>
<tbody>
<tr>
<td>“var”</td>
<td>"abc"</td>
<td>module.exports = abc;</td>
</tr>
<tr>
<td>“var”</td>
<td>"abc.def"</td>
<td>module.exports = abc.def;</td>
</tr>
<tr>
<td>“this”</td>
<td>"abc"</td>
<td>(function() { module.exports = this["abc"]; }());</td>
</tr>
<tr>
<td>“this”</td>
<td>["abc", "def"]</td>
<td>(function() { module.exports = this["abc"]["def"]; }());</td>
</tr>
<tr>
<td>“commonjs”</td>
<td>"abc"</td>
<td>module.exports = require("abc");</td>
</tr>
<tr>
<td>“commonjs”</td>
<td>["abc", "def"]</td>
<td>module.exports = require("abc").def;</td>
</tr>
<tr>
<td>“amd”</td>
<td>"abc"</td>
<td>define(["abc"], function(X) { module.exports = X; })</td>
</tr>
<tr>
<td>“umd”</td>
<td>"abc"</td>
<td>everything above</td>
</tr>
</tbody>
</table>

<p>All the ways to set an external dep are easy to understand with the official doc.</p>
<p>The only thing I'd recommend is to not mix your <code>libraryTarget</code> and the type of the <code>externals</code>. Like:</p>
<pre><code class="lang-javascript">output:{
    <span class="hljs-attr">libraryTarget</span>: <span class="hljs-string">"amd"</span>
},
externals = [
    {
        <span class="hljs-string">"./extLibrary"</span>: <span class="hljs-string">"var extLibrary"</span>
    }
}
</code></pre>
<p>This would be <strong>invalid</strong>, as <code>extLibrary</code> wouldn't exist as a variable in the final bundle, as the bundle is defined as amd.</p>
<p>Webpack will give more importance to your <code>libraryTarget</code> than to your external type, "correcting" them. But I wouldn't relay on it that much. Keep it consistent!</p>
<p>Some official warnings before ending with this configuartion:</p>
<blockquote>
<p>Enforcing amd or umd in a external value will break if not compiling as amd/umd target.</p>
<p>Note: If using umd you can specify an object as external value with property commonjs, commonjs2, amd and root to set different values for each import kind.</p>
</blockquote>
<p>Hope it helped, give me feedback if I'm missing something or if I'm wrong in something!</p>
]]></content:encoded></item><item><title><![CDATA[Javascript ES6 Classes for Java Developers]]></title><description><![CDATA[I'm part Java part Javascript developer, so one of the first things I wanted to know when I saw the new ES6 classes 
is what they can do, how are they similar to Java classes. 
So these are my findings:
We will analyze: 

Inheritance
Accessors
Static...]]></description><link>https://tomasalabes.me/javascript-es6-classes-for-java-developers</link><guid isPermaLink="true">https://tomasalabes.me/javascript-es6-classes-for-java-developers</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Java]]></category><category><![CDATA[ES6]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Wed, 16 Sep 2015 12:30:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/fPkvU7RDmCo/upload/da08f518ce5c31cfa91300193da9259b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I'm part Java part Javascript developer, so one of the first things I wanted to know when I saw the new ES6 classes 
is what they can do, how are they similar to Java classes. 
So these are my findings:</p>
<p>We will analyze: </p>
<ol>
<li><a class="post-section-overview" href="#inheritance">Inheritance</a></li>
<li><a class="post-section-overview" href="#accessors">Accessors</a></li>
<li><a class="post-section-overview" href="#static-methods">Static Methods</a></li>
<li><a class="post-section-overview" href="#static-fields">Static Fields</a></li>
<li><a class="post-section-overview" href="#abstract-classes">Abstract Classes</a></li>
<li><a class="post-section-overview" href="#abstract-methods">Abstract Methods</a></li>
<li><a class="post-section-overview" href="#private-fields">Private Fields</a></li>
<li><a class="post-section-overview" href="#functions-overloading">Functions Overloading</a></li>
<li><a class="post-section-overview" href="#interfaces">Interfaces</a></li>
</ol>
<h2 id="heading-inheritance">Inheritance</h2>
<p>Inheritance is one of the building blocks of Java and OOP, and it's one of the things that ES6 already has,
lets see how it looks in Javascript.</p>
<pre><code class="lang-javascript">
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Warrior</span> </span>{

    <span class="hljs-keyword">constructor</span>(name) {
        <span class="hljs-built_in">this</span>._name = name;
        <span class="hljs-built_in">this</span>._health = <span class="hljs-number">100</span>;
    }

    heal(amount) {
        <span class="hljs-built_in">this</span>._health = <span class="hljs-built_in">Math</span>.min(<span class="hljs-built_in">this</span>._health + amount, <span class="hljs-number">100</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Ninja</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Warrior</span> </span>{

    <span class="hljs-keyword">constructor</span>(name) {
        <span class="hljs-built_in">super</span>(name);
    }

    heal(amount) {
        <span class="hljs-built_in">super</span>.heal(amount * <span class="hljs-number">1.2</span>);
    }

}
</code></pre>
<p>Everything here is almost self-explanatory, it uses a a very similar syntax than Java. Instead of having the constructor 
with the name of the class, you just put <code>constructor</code> and the parameters for it.<br /><br /></p>
<h3 id="heading-default-constructor-and-the-function-parameters">Default constructor and the "..." function parameters</h3>
<p>If you don’t specify a constructor for a base class, the following constructor is used:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">constructor</span>() {}
</code></pre>
<p>For derived classes, the following default constructor is used:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">constructor</span>(...args) {
    <span class="hljs-built_in">super</span>(...args);
}
</code></pre>
<p>So here we can see two things, how default constructors are, and the <code>...args</code> syntax that is also used in Java to pass
as many arguments as you want. The array of arguments already existed in javascript using the <code>arguments</code> object, 
but now we can do something like:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span> </span>{

    receiveWhatever(aNumber, ...rest) {
        <span class="hljs-built_in">console</span>.log(aNumber);

        rest.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">thing</span>)</span>{
            <span class="hljs-built_in">console</span>.log(thing);
        });
    }

}
</code></pre>
<h2 id="heading-accessors">Accessors</h2>
<p>We have the ability to define getters and setters for our fields. So we can access them as any other object property.</p>
<pre><code class="lang-javascript">
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Warrior</span> </span>{

    <span class="hljs-keyword">constructor</span>(name) {
        <span class="hljs-built_in">this</span>._name = name;
        <span class="hljs-built_in">this</span>._health = <span class="hljs-number">100</span>;
    }

    <span class="hljs-keyword">get</span> <span class="hljs-title">health</span>(){
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._health;
    }
}

<span class="hljs-keyword">let</span> donatello = <span class="hljs-keyword">new</span> Ninja(<span class="hljs-string">"Donatello"</span>);
<span class="hljs-built_in">console</span>.log(donatello._health); <span class="hljs-comment">// 100 (this will still work...) but:</span>
<span class="hljs-built_in">console</span>.log(donatello.health); <span class="hljs-comment">// 100, nicer and you can do things in the getter</span>

donatello.health = <span class="hljs-number">80</span>; <span class="hljs-comment">// Error!</span>
<span class="hljs-comment">// TypeError: Cannot set property health of # which has only a getter at eval</span>

donatello._health = <span class="hljs-number">80</span>; <span class="hljs-comment">// You can, but shame on you...</span>
</code></pre>
<p>When we define a getter (and no setter), the variable becomes read-only with the getter/setter name, but you can still change
it when the variable name, "_health" in this case, but is not a good practice! </p>
<p>Either use the accessors, or don't.</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// [...]</span>

    <span class="hljs-keyword">set</span> <span class="hljs-title">health</span>(<span class="hljs-params">newHealth</span>){
        <span class="hljs-built_in">this</span>._health = newHealth;
    }

}

<span class="hljs-keyword">let</span> donatello = <span class="hljs-keyword">new</span> Ninja(<span class="hljs-string">"Donatello"</span>);
donatello.health = <span class="hljs-number">80</span>; <span class="hljs-comment">// Right way of doing it</span>
</code></pre>
<h2 id="heading-static-methods">Static Methods</h2>
<p>Static methods are also something included in ES6, are easy and similar to Java. </p>
<pre><code class="lang-javascript">
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span> </span>{
    <span class="hljs-keyword">static</span> classMethod() {
        <span class="hljs-keyword">return</span> <span class="hljs-string">'hello'</span>;
    }
}

Foo.classMethod(); <span class="hljs-comment">// 'hello'</span>
</code></pre>
<p>Very similar to java.
One thing you can do in Javascript but can't in Java is the following:</p>
<pre><code class="lang-javascript">
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span> </span>{
    <span class="hljs-keyword">static</span> classMethod() {
        <span class="hljs-keyword">return</span> <span class="hljs-string">'hello'</span>;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bar</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Foo</span> </span>{
    <span class="hljs-keyword">static</span> classMethod() {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">super</span>.classMethod() + <span class="hljs-string">', too'</span>;
    }
}
Bar.classMethod(); <span class="hljs-comment">// 'hello, too'</span>
</code></pre>
<p>From the derived class you can override and call your parents static method. </p>
<p>Why can't you in java? <a target="_blank" href="http://stackoverflow.com/questions/2223386/why-doesnt-java-allow-overriding-of-static-methods">Answer</a>.</p>
<h2 id="heading-static-fields">Static Fields</h2>
<p>They are not baked-in ES6 but there is a <a target="_blank" href="https://github.com/jeffmo/es-class-properties">discussion</a>
about it for ES7. Right now you can simulate the functionality like this: </p>
<pre><code class="lang-javascript">
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span> </span>{
    <span class="hljs-keyword">constructor</span>() {}
}

<span class="hljs-comment">//definition</span>
<span class="hljs-keyword">const</span> staticNumber = <span class="hljs-number">5</span>;
<span class="hljs-keyword">const</span> staticObj = { <span class="hljs-attr">prop</span>: <span class="hljs-number">5</span> };
Foo.staticNumber = staticNumber;
Foo.staticObj = staticObj;
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// Examples of use</span>

<span class="hljs-keyword">new</span> Foo().staticNumber; <span class="hljs-comment">//undefined</span>
Foo.staticNumber; <span class="hljs-comment">// 5</span>
Foo.staticObj; <span class="hljs-comment">//{ prop: 5 }</span>

Foo.staticObj.prop = <span class="hljs-number">2</span>; <span class="hljs-comment">// Error! const can't be changed! </span>

Foo.staticVar = <span class="hljs-number">10</span>; <span class="hljs-comment">// WARNING: overriding static field value</span>
Foo.staticObj = {<span class="hljs-attr">prop</span>: <span class="hljs-string">"hello"</span>}; <span class="hljs-comment">// WARNING: overriding static field value</span>

Foo.staticVar; <span class="hljs-comment">// 10</span>
Foo.staticObj; <span class="hljs-comment">// {prop: "hello"};</span>
</code></pre>
<p>But as we saw in the example it can be changed easily...</p>
<h2 id="heading-abstract-classes">Abstract classes</h2>
<p>This concept is not implemented in ES6 or ES7, and I couldn't find anything official about it, but I found a way to mimic them
in this <a target="_blank" href="http://stackoverflow.com/questions/29480569/does-ecmascript-6-have-a-convention-for-abstract-classes">Stack Overflow answer</a>.</p>
<pre><code class="lang-javascript">
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Abstract</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">new</span>.target === Abstract) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">"Cannot construct Abstract instances directly"</span>);
    }
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Derived</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Abstract</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">super</span>();
    <span class="hljs-comment">// more Derived-specific stuff here, maybe</span>
  }
}

<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> Abstract(); <span class="hljs-comment">// new.target is Abstract, so it throws Error</span>
<span class="hljs-keyword">const</span> b = <span class="hljs-keyword">new</span> Derived(); <span class="hljs-comment">// new.target is Derived, so no error</span>
</code></pre>
<p>It doesn't seem a super hacky way of implementing it.</p>
<h2 id="heading-abstract-methods">Abstract Methods</h2>
<p>Similar thing for abstract methods.</p>
<pre><code class="lang-javascript">
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Abstract</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.method === <span class="hljs-literal">undefined</span>) {
      <span class="hljs-comment">// or maybe test typeof this.method === "function"</span>
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">"Must override method"</span>);
    }
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Derived1</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Abstract</span> </span>{}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Derived2</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Abstract</span> </span>{
  method() {}
}

<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> Abstract(); <span class="hljs-comment">// this.method is undefined; error</span>
<span class="hljs-keyword">const</span> b = <span class="hljs-keyword">new</span> Derived1(); <span class="hljs-comment">// this.method is undefined; error</span>
<span class="hljs-keyword">const</span> c = <span class="hljs-keyword">new</span> Derived2(); <span class="hljs-comment">// this.method is Derived2.prototype.method; no error</span>
</code></pre>
<h2 id="heading-private-fields">Private Fields</h2>
<p>Private fields are not supported in any ES right now, but there are a couple of 
new structures in ES6 that let you emulate the private scope.
I've read several good articles about it, I recommend <a target="_blank" href="https://curiosity-driven.org/private-properties-in-javascript">Private Properties in Javascript</a>.</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> private = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Warrior</span> </span>{

    <span class="hljs-keyword">constructor</span>(name) {
        <span class="hljs-built_in">this</span>._name = name;

        private.set(<span class="hljs-built_in">this</span>, {
            <span class="hljs-attr">health</span>: <span class="hljs-number">100</span>
        });

    }

    heal(amount) {
        <span class="hljs-built_in">this</span>._health = <span class="hljs-built_in">Math</span>.min(<span class="hljs-built_in">this</span>._health + amount, <span class="hljs-number">100</span>);
    }

    <span class="hljs-keyword">get</span> <span class="hljs-title">health</span>(){
        <span class="hljs-keyword">return</span> private.get(<span class="hljs-built_in">this</span>).health;
    }
}
</code></pre>
<p>Although the <code>WeakMap</code> is a new structure for Javascript, for Java is not: <a target="_blank" href="http://docs.oracle.com/javase/8/docs/api/java/util/WeakHashMap.html">WeakHashMap</a>.</p>
<blockquote>
<p>The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. The keys must be objects and the values can be arbitrary values.</p>
</blockquote>
<p><span>WARNING</span></p>
<p>The above <code>private</code> WeakMap is shared among all Warrior instances, so potentially you can access another warrior's
health. It's a disadvantage of this implementation.  </p>
<h2 id="heading-functions-overloading">Functions Overloading</h2>
<p>This functionality have never existed in Javascript and there is no plan on supporting it. But this es mainly because
Javascript, as a dynamically typed language, make this impossible:</p>
<pre><code class="lang-javascript">
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{

    say(what) { <span class="hljs-comment">//string</span>
        <span class="hljs-built_in">console</span>.log(thing);
    }

    say(things) { <span class="hljs-comment">//array</span>
        things.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">thing</span>)</span>{
            <span class="hljs-built_in">console</span>.log(thing);
        });

    }

    say() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"blah"</span>)
    }

}
</code></pre>
<p>Javascript has no type checking on arguments or required quantity of arguments, so you can just have one
implementation of <code>say()</code>. 
You can adapt to what arguments were passed to it by checking the type, presence or quantity of arguments.</p>
<h2 id="heading-interfaces">Interfaces</h2>
<p>There is no concept of interface whatsoever in any version of javascript, you can find interfaces in
<a target="_blank" href="www.typescriptlang.org/">Typescript</a> or <a target="_blank" href="https://www.dartlang.org/">Dart</a> than then are compiled to ES5 javascript
but nothing native.</p>
<p>There is a native rather ugly workaround in this <a target="_blank" href="http://stackoverflow.com/questions/3710275/does-javascript-have-the-interface-type-such-as-javas-interface">StackOverflow answer</a>
if you <strong>really</strong> need it native.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Despite not having all the OOP concepts and constructs that Java has (remember javascript was born and is as a prototype based language), 
it's possible to have a lot of the functionality, some are more hacky than others but hey, 
if you have programmed in js for a while you are scared of nothing. </p>
<p>Am I missing something or is there a better way to do these things?</p>
<p>Comments or improvements are appreciated!</p>
<p>Thanks!</p>
<hr />
<p>Resources:</p>
<ol>
<li><a target="_blank" href="http://www.2ality.com/2015/02/es6-classes-final.html">www.2ality.com</a></li>
<li><a target="_blank" href="http://es6-features.org/#ClassDefinition">es6-features.org</a></li>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap">MDN</a></li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Adding CSS with Requirejs]]></title><description><![CDATA[Problem
In one of my projects I was using requirejs and I had the situation where I had html templates with links to external css files, after I appended these templates to the DOM, the javascript that needed to use that styled DOM didn't have the st...]]></description><link>https://tomasalabes.me/adding-css-with-requirejs</link><guid isPermaLink="true">https://tomasalabes.me/adding-css-with-requirejs</guid><category><![CDATA[requirejs]]></category><category><![CDATA[CSS]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Sat, 12 Sep 2015 12:30:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723639458813/c61aa08d-f1a8-42fd-a656-bd1b2c8bfc78.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem">Problem</h2>
<p>In one of my projects I was using requirejs and I had the situation where I had html templates with links to external css files, after I appended these templates to the DOM, the javascript that needed to use that styled DOM didn't have the style applied...why? easy, the css file was not there yet to apply the style. 
I also wanted to have all the app bundled into 1 single file, css included, to avoid this problem. So what did I do?</p>
<p><strong>TLDR?</strong></p>
<p>I used the same <a target="_blank" href="https://github.com/requirejs/text">requirejs-text plugin</a> that I used for the html templates but for the css an inject it as a <code>&lt;style&gt;</code> tag. </p>
<p>That way, when I bundle all my files into 1, I already bundled the css (as text) and inject it immediatly when I needed, and the code that is executed after it already has the style applied. Take a look at the <a class="post-section-overview" href="#solution">solution</a>.</p>
<h2 id="heading-how-i-got-to-that-solution">How I got to that solution</h2>
<p>I first used the <a target="_blank" href="https://github.com/guybedford/require-css">require-css</a> plugin:</p>
<pre><code class="lang-javascript">    define([<span class="hljs-string">'css!style'</span>, <span class="hljs-string">'myJavascript'</span>], <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">style, myJavascript</span>) </span>{
        <span class="hljs-comment">// in this case the plugin adds a &lt;link&gt; for the css, </span>
        <span class="hljs-comment">// and calls this code on the onload of it (and the js).</span>
    });
</code></pre>
<p>This would do the job, but when I wanted to bundle all the css and js files into 1 big file with this code:</p>
<pre><code class="lang-javascript">    define([<span class="hljs-string">'someJs'</span>], <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">someJs</span>) </span>{
        <span class="hljs-keyword">if</span>(someCondition){
            <span class="hljs-built_in">require</span>([<span class="hljs-string">'css!style'</span>, <span class="hljs-string">'myJavascript'</span>], <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">style, myJavascript</span>) </span>{
                <span class="hljs-comment">// if some condition applies, I want to load my css</span>
                <span class="hljs-comment">// and work with the js that uses the styled DOM</span>
            });
        }
    });
</code></pre>
<p>In this case, when I bundled everything, the css weren't bundled as well, so I needed to wait for the css to arrive to execute the dependant code. It makes sense but I want the css to be bundled too so the execution of that code is instant.</p>
<h2 id="heading-solutionidsolution"><a target="_blank">Solution</a></h2>
<p>So the way i did that was using the same <a target="_blank" href="https://github.com/requirejs/text">requirejs-text plugin</a> that I used for the html templates, but for the css.</p>
<pre><code class="lang-javascript">    define([<span class="hljs-string">'someJs'</span>], <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">someJs</span>) </span>{
        <span class="hljs-keyword">if</span>(someCondition){
            <span class="hljs-built_in">require</span>([<span class="hljs-string">'text!style'</span>, <span class="hljs-string">'myJavascript'</span>], <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">style, myJavascript</span>) </span>{
                <span class="hljs-comment">// this way it's immedietly injected in the html</span>
                $(<span class="hljs-string">'head'</span>).append(<span class="hljs-string">'&lt;style&gt;'</span> + style + <span class="hljs-string">'&lt;/style&gt;'</span>);    
                <span class="hljs-comment">// and work with the js that uses the styled DOM</span>
            });
        }
    });
</code></pre>
<p>The only disadvantage that I see it that I will bundle all the css with the rest of the app when perhaps I won't use them all. But I don't mind adding 0.5 kb to the file to improve the UX of the app.</p>
<p>This isn't really rocket science but in production I didn't want to wait for external css to be loaded when the rest of the app is already in the client. So I found these easy and simple solution to it.</p>
<p>By the way, I was using grunt for all these, I know webpack has this already built-in but I didn't have the chance to use it.</p>
<p>That's it, thanks!</p>
]]></content:encoded></item><item><title><![CDATA[How to register your library or component in Bower]]></title><description><![CDATA[Bower is a package manager for the web. It offers a generic, un-opinionated solution to the problem of front-end package management.
Bower depends on Node and npm. It's installed globally using npm:
npm install -g bower
To register a new package:

Th...]]></description><link>https://tomasalabes.me/how-to-register-your-library-or-component-in-bower</link><guid isPermaLink="true">https://tomasalabes.me/how-to-register-your-library-or-component-in-bower</guid><category><![CDATA[bower]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Mon, 03 Jun 2013 12:30:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723639512099/2650906f-0a90-443a-8d4f-1047a3bcaf30.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Bower is a package manager for the web. It offers a generic, un-opinionated solution to the problem of front-end package management.</p>
<p>Bower depends on Node and npm. It's installed globally using npm:</p>
<p><code>npm install -g bower</code></p>
<p>To register a new package:</p>
<ul>
<li>There must be a valid manifest JSON in the current working directory. </li>
<li>Your package should use semver Git tags. </li>
<li>Your package must be available at a Git endpoint (e.g., GitHub); remember to push your Git tags! </li>
</ul>
<p>You can use bower init to generate the valid manifest json</p>
<pre><code class="lang-shell">bower init
</code></pre>
<p>It will produce something like this:</p>
<pre><code class="lang-javascript">{
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"appName"</span>,
  <span class="hljs-string">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-string">"main"</span>: [
    <span class="hljs-string">"app.js"</span>
  ],
  <span class="hljs-string">"ignore"</span>: [
    <span class="hljs-string">"**/.*"</span>,
    <span class="hljs-string">"node_modules"</span>,
    <span class="hljs-string">"components"</span>
  ],
  <span class="hljs-string">"dependencies"</span>: {
    <span class="hljs-string">"myDep"</span>: <span class="hljs-string">"latest"</span>,
    <span class="hljs-string">"myDep2"</span>: <span class="hljs-string">"2.0.0"</span>
  }
}
</code></pre>
<p>Then to register your app:</p>
<pre><code class="lang-sh">bower register [app name] [git endpoint]

// example:
bower register raphael.backbone git://github.com/tomasAlabes/backbone.raphael.git
Registering a package will make it visible and installable via the registry.
Proceed (y/n)? y
registered backbone.raphael to git://github.com/tomasAlabes/backbone.raphael.git
</code></pre>
<p>And now your library is ready to be used via bower :)
Use my library as an example if you want: <a target="_blank" href="https://github.com/tomasAlabes/backbone.raphael">backbone.raphael</a></p>
<p>Enjoy!</p>
]]></content:encoded></item><item><title><![CDATA[SVG/VML views in your Backbone app with Raphael]]></title><description><![CDATA[Hi! Now:
Presenting backbone.raphael
You may already know the famous Backbone javascript library that lets you build an MV* architecture in the client. And perhaps you also know Raphael, that gives you the opportunity to abstract you from the browser...]]></description><link>https://tomasalabes.me/svgvml-views-in-your-backbone-app-with-raphael</link><guid isPermaLink="true">https://tomasalabes.me/svgvml-views-in-your-backbone-app-with-raphael</guid><category><![CDATA[VML]]></category><category><![CDATA[SVG]]></category><category><![CDATA[BackboneJS]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Tue, 28 May 2013 12:30:16 GMT</pubDate><content:encoded><![CDATA[<p>Hi! Now:</p>
<p>Presenting <a target="_blank" href="https://github.com/tomasAlabes/backbone.raphael">backbone.raphael</a></p>
<p>You may already know the famous <a target="_blank" href="http://backbonejs.org/">Backbone</a> javascript library that lets you build an MV* architecture in the client. And perhaps you also know Raphael, that gives you the opportunity to abstract you from the browser you are using and let you work with SVG o VML indifferently.</p>
<p>In Backbone, the V was thought for html views, but with the flexibility that backbone offers and a little bit of ingenuity we can extend backbone and let your app embrace the vectorial images in your browser.</p>
<p>For this, I created/am creating a Backbone extension that easily lets you do that, called backbone.raphael. It is a simple tweak of how Backbone handles Views events, and how Raphael does it.
How do I use it?</p>
<ol>
<li>Add backbone.raphael.js after backbone.js in your html</li>
</ol>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"backbone.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-comment">&lt;!-- The extension  --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"backbone.raphael.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>This will enable you to use the new Backbone.RaphaelView</p>
<ol start="2">
<li>How to use it</li>
</ol>
<p>First:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//Raphael root element</span>
<span class="hljs-keyword">var</span> paper = Raphael(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">300</span>, <span class="hljs-number">640</span>);

<span class="hljs-comment">// Usual backbone model, why change it if the View is the new thing?</span>
<span class="hljs-keyword">var</span> CircleModel = Backbone.Model.extend();
Now we create the view
<span class="hljs-comment">//This view extends from Backbone.View</span>
<span class="hljs-keyword">var</span> CircleView = Backbone.RaphaelView.extend({

    <span class="hljs-attr">initialize</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">var</span> model = <span class="hljs-built_in">this</span>.model;
        <span class="hljs-built_in">this</span>.listenTo(model, <span class="hljs-string">"change"</span>, <span class="hljs-built_in">this</span>.render);

        <span class="hljs-comment">// Create raphael element from the model</span>
        <span class="hljs-keyword">var</span> circle = paper.circle(model.get(<span class="hljs-string">"x"</span>), model.get(<span class="hljs-string">"y"</span>), model.get(<span class="hljs-string">"radio"</span>)).attr({<span class="hljs-attr">fill</span>: model.get(<span class="hljs-string">"color"</span>)});

        <span class="hljs-comment">// Set the element of the view</span>
        <span class="hljs-built_in">this</span>.setElement(circle);
    },

    <span class="hljs-attr">events</span>: {
        <span class="hljs-comment">// Any raphael event, no selector needed</span>
        <span class="hljs-string">"click"</span>: <span class="hljs-string">"sayType"</span>,
        <span class="hljs-comment">// Or any custom event</span>
        <span class="hljs-string">"foo"</span>: <span class="hljs-string">"sayType"</span>
    },

    <span class="hljs-attr">sayType</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">evt</span>)</span>{
        <span class="hljs-built_in">console</span>.log(evt.type);
    },

    <span class="hljs-attr">render</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">var</span> circle = <span class="hljs-built_in">this</span>.el;
        <span class="hljs-keyword">var</span> model = <span class="hljs-built_in">this</span>.model;

        <span class="hljs-comment">//When the model changes, so the element</span>
        circle.attr({
            <span class="hljs-attr">cx</span>: model.get(<span class="hljs-string">"x"</span>),
            <span class="hljs-attr">cy</span>: model.get(<span class="hljs-string">"y"</span>),
            <span class="hljs-attr">r</span>: model.get(<span class="hljs-string">"radio"</span>),
            <span class="hljs-attr">fill</span>: model.get(<span class="hljs-string">"color"</span>)
        });
    }

});
</code></pre>
<p>Now is time for creating some real objects:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> model = <span class="hljs-keyword">new</span> CircleModel({
    <span class="hljs-attr">x</span>: <span class="hljs-number">100</span>,
    <span class="hljs-attr">y</span>: <span class="hljs-number">150</span>,
    <span class="hljs-attr">radio</span>: <span class="hljs-number">50</span>,
    <span class="hljs-attr">color</span>: <span class="hljs-string">"blue"</span>
});

<span class="hljs-keyword">var</span> view = <span class="hljs-keyword">new</span> CircleView({
    <span class="hljs-attr">model</span>: model
});
</code></pre>
<p>Then in your app you can trigger the custom events you binded:</p>
<pre><code class="lang-javascript">view.trigger(<span class="hljs-string">"foo"</span>);
</code></pre>
<p>In my <a target="_blank" href="https://github.com/tomasAlabes/backbone.raphael">github</a> repo it is the source code and a more complex sample app for you to see. This extension is still in development but is usable today.</p>
<p>Enjoy!</p>
]]></content:encoded></item><item><title><![CDATA[Introduction to RaphaelJS]]></title><description><![CDATA[Raphaël is a small JavaScript library that should simplify your work with vector graphics on the web. If you want to create your own specific chart or image crop and rotate widget, for example, you can achieve it simply and easily with this library.
...]]></description><link>https://tomasalabes.me/introduction-to-raphaeljs</link><guid isPermaLink="true">https://tomasalabes.me/introduction-to-raphaeljs</guid><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Wed, 13 Mar 2013 12:30:16 GMT</pubDate><content:encoded><![CDATA[<p>Raphaël is a small JavaScript library that should simplify your work with vector graphics on the web. If you want to create your own specific chart or image crop and rotate widget, for example, you can achieve it simply and easily with this library.</p>
<p>I made this presentation to introduce this library in the easier way I can, hope that anyone interested like it and learn from it.
Enjoy!</p>
<p><iframe height="356" src="http://www.slideshare.net/slideshow/embed_code/16865254" style="align:center;border-width:1px 1px 0;border:1px solid #CCC;margin-bottom:5px" width="427"> </iframe> <br /></p>
<p></p><div>
<strong> <a href="http://www.slideshare.net/TomasAlabes/raphael" target="_blank">Raphael</a> </strong> from <strong><a href="http://www.slideshare.net/TomasAlabes" target="_blank">Tomas Alabes</a></strong><p></p>
</div>]]></content:encoded></item><item><title><![CDATA[Book review: Learning Raphaël JS Vector Graphics]]></title><description><![CDATA[Book Review: Learning Raphaël JS Vector Graphics
Learning Raphaël JS Vector Graphics is Damian Dawber's new book about Raphaël. It was released on May and has been written for anyone with an interest in frontend browser technologies with little or no...]]></description><link>https://tomasalabes.me/book-review-learning-raphael-js-vector-graphics</link><guid isPermaLink="true">https://tomasalabes.me/book-review-learning-raphael-js-vector-graphics</guid><category><![CDATA[book review]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Wed, 13 Mar 2013 12:30:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Ny3se6T0V7c/upload/bcc443caf028478ed827059bd9cce7ab.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Book Review: Learning Raphaël JS Vector Graphics</p>
<p>Learning Raphaël JS Vector Graphics is Damian Dawber's new book about Raphaël. It was released on May and has been written for anyone with an interest in frontend browser technologies with little or no knowledge of vector graphics drawing.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1723639615207/56a8073b-36ca-489a-b41e-b92ff41c3a3d.jpeg" alt class="image--center mx-auto" /></p>
<p>The book starts introducing the library and the background of vector drawings, explaining how it was done in the IE times, how it is done now, and how the SVG spec is evolving. Into the core of the book it goes over almost all library functionalities, from the basics like the canvas, basic shapes, text and images, to paths, transformations and animations. In general, it gives basic examples of the functionalities, not going into too much depth. One of the things that stands out are the examples of custom attributes, in my opinion, a really nice functionality that is not very used. All examples are uploaded in the book samples page.</p>
<p>Then it has a specific chapter for working with existing SVGs, a chapter worth reading if you are going to work with SVG not generated by Raphael.</p>
<p>Finally the author creates a suite of social media visualisations using all the things explained in the previous chapters using jQuery for DOM interaction. He mixes paths, custom attributes, animations, and DOM interaction for building widgets with social media data. Complex enough for all the concepts explained before. And then to finish, explains where Raphael is going and mention some supplementary material.</p>
<p>In summary, great book to get to know Raphael and become an experienced user, but not enough to build a complex app with it. I would have liked a more "app example" than a widget example.</p>
<p>Do you want to start using Raphael? This is definitely a good start.</p>
]]></content:encoded></item><item><title><![CDATA[Handling attackers in your web application]]></title><description><![CDATA[Anyone designing an application for which security is remotely important must assume that it will be directly targeted by dedicated and skilled attackers. A key function of the application’s security mechanisms is being able to handle and react to th...]]></description><link>https://tomasalabes.me/handling-attackers-in-your-web-application</link><guid isPermaLink="true">https://tomasalabes.me/handling-attackers-in-your-web-application</guid><category><![CDATA[#cybersecurity]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Wed, 13 Mar 2013 12:30:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/SYofhg_IX3A/upload/a0fe6cc3a9e298594d4964b282c98679.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Anyone designing an application for which security is remotely important must assume that it will be directly targeted by dedicated and skilled attackers. A key function of the application’s security mechanisms is being able to handle and react to these attacks in a controlled way.</p>
<p>Handling Errors</p>
<p>However careful an application’s developers are when validating user input, it is virtually inevitable that some unanticipated errors will occur.
A key defense mechanism is for the application to handle unexpected errors gracefully, and either recover from them or present a suitable error message to the user.
In a production context, the application should never return any system-generated messages or other debug information in its responses.
Overly verbose error messages can greatly assist malicious users in furthering their attacks against the application. In some situations, an attacker can leverage defective error handling to retrieve sensitive information within the error messages themselves, providing a valuable channel for stealing data from the application.
Effective error handling is often integrated with the application’s logging mechanisms, which record as much debug information as possible about unanticipated errors.
Maintaining Audit Logs</p>
<p>Audit logs are valuable primarily when investigating intrusion attempts against an application.
Effective audit logs should enable the application’s owners to understand exactly what has taken place, which vulnerabilities (if any) were exploited, whether the attacker gained unauthorized access to data or performed any unauthorized actions, and, as far as possible, provide evidence of the intruder’s identity.
An effective approach is to store audit logs on an autonomous system that accepts only update messages from the main application. In some situations, logs may be flushed to write-once media to ensure their integrity in the event of a successful attack.
Alerting Administrators</p>
<p>Audit logs enable an application’s owners to retrospectively investigate intrusion attempts and, if possible, take legal action against the perpetrator. However, in many situations it is desirable to take much more immediate action, in real time, in response to attempted attacks.
In most situations, alerting mechanisms must balance the conflicting objectives of reporting each genuine attack reliably and of not generating so many alerts that these come to be ignored.
Anomalous events monitored by alerting mechanisms often include the following:
Usage anomalies, such as large numbers of requests being received from a single IP address or user, indicating a scripted attack 
Business anomalies, such as an unusual number of funds transfers being made to or from a single bank account 
Requests containing known attack strings
Requests where data that is hidden from ordinary users has been modified
In any security-critical application, the most effective way to implement real-time alerting is to integrate this tightly with the application’s input validation mechanisms and other controls.
Reacting to Attacks </p>
<p>In addition to alerting administrators, many security-critical applications contain built-in mechanisms to react defensively to users who are identified as potentially malicious.
Some applications take automatic reactive measures to frustrate the activities of an attacker who is working systematically to discover any application defect.
Although these measures will not defeat the most patient and determined attacker, they will deter many more casual attackers and will buy additional time for administrators to monitor the situation and take more drastic action if desired.
Reacting to apparent attackers is not, of course, a substitute for fixing any vulnerabilities that exist within the application. But placing further obstacles in the way of an attacker is an effective defense-in-depth measure that reduces the likelihood that any residual vulnerabilities will be found and exploited.
Conclusion</p>
<p>These mechanisms often incorporate a mix of defensive and offensive measures designed to frustrate an attacker as much as possible and give the application’s owners appropriate notification and evidence of what has taken place. </p>
<p>This have been partially extracted from a wonderful book about web applications security: The Web Application Hacker's Handbook: Finding and Exploiting Security Flaws. If you would like to dive deeper into any of this subjects I encourage you to buy it.</p>
<p>Have this mechanisms in mind and use them if you can.</p>
<p>Tomas Alabes</p>
]]></content:encoded></item><item><title><![CDATA[How to get the latest tweets of a group of people with Twitter REST API]]></title><description><![CDATA[This seems like a easy or at least common task of twitter right? Well...I thought so, but it gave me a headache for half an hour.
I first tried to use the twitter search API (I recommend you using this API Tester for testing the api from twitter itse...]]></description><link>https://tomasalabes.me/how-to-get-the-latest-tweets-of-a-group-of-people-with-twitter-rest-api</link><guid isPermaLink="true">https://tomasalabes.me/how-to-get-the-latest-tweets-of-a-group-of-people-with-twitter-rest-api</guid><category><![CDATA[Twitter]]></category><category><![CDATA[REST API]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Fri, 08 Mar 2013 12:30:16 GMT</pubDate><content:encoded><![CDATA[<p>This seems like a easy or at least common task of twitter right? Well...I thought so, but it gave me a headache for half an hour.</p>
<p>I first tried to use the twitter search API (I recommend you using this API Tester for testing the api from twitter itself) , using queries like "from:tweeterA or from:tweeterB" but I wanted from like 50 people, pretty big query... And:</p>
<p>Twitter's search is optimized to serve relevant tweets to end-users in response to direct, non-recurring queries such as #hashtags, URLs, domains, and keywords. The Search API is an interface to this search engine. Our search service is not meant to be an exhaustive archive of public tweets and not all tweets are indexed or returned. Some results are refined to better combat spam and increase relevance.</p>
<p>So definitively this was not the answer...
It HAD to be easy! Googling and googling I found the answer to my humble question: lists.</p>
<p>For a collection of recent Tweets by more than one user, consider creating a Twitter List and leveraging the list timeline.
A list is a curated group of Twitter users. You can create your own lists or subscribe to lists created by others. Viewing a list timeline will show you a stream of Tweets from only the users on that list.
More on lists.</p>
<p>So in my twitter account made a list, add all the people I wanted to follow and use the GET list statuses service.</p>
<p>Here is the obligatory data the service needs, of course you can view more info in the official documentation of it.</p>
<p>Now to the code.</p>
<p>I'm using nodeJS in my server (remember we now have to authenticate to use even some of the simplest services of the twitter API), the configuration or how to query the server can be seen in other post of mine.</p>
<p>An example of use would be the following:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> config = {<span class="hljs-attr">listId</span>: <span class="hljs-string">"86236722"</span>, <span class="hljs-attr">ownerId</span>: <span class="hljs-string">"tomasAlabes"</span>, <span class="hljs-attr">count</span>: <span class="hljs-number">10</span>, <span class="hljs-attr">slug</span>: <span class="hljs-string">"poli-tweets-com-ar"</span>}
<span class="hljs-built_in">exports</span>.getLatestTweetsFromList = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">config, callback</span>)</span>{
    oauth.get(<span class="hljs-string">"http://api.twitter.com/1.1/lists/statuses.json?"</span>+
<span class="hljs-string">"owner_id="</span>+config.ownerId+
<span class="hljs-string">"&amp;count="</span>+config.count+
<span class="hljs-string">"&amp;list_id="</span>+config.listId+
<span class="hljs-string">"&amp;slug="</span>+config.slug, access_token, access_token_secret, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error, data</span>) </span>{
        <span class="hljs-keyword">var</span> result;
        <span class="hljs-keyword">if</span>(error){
            result = {<span class="hljs-attr">error</span>: error};
        }<span class="hljs-keyword">else</span>{
            result = data;
        }
        <span class="hljs-built_in">console</span>.log(data);
        callback(result);
    });
};
</code></pre>
<p>Don't know how to get your list id? Check this.</p>
<p>Hope it helps,
Enjoy!</p>
]]></content:encoded></item><item><title><![CDATA[Convert SVG to Raphael in one step]]></title><description><![CDATA[Perhaps you have heard of the Raphaël library. Raphaël is a small JavaScript library that should simplify your work with vector graphics on the web. It's open-source and its one of the most famous libraries on github, the most popular for svg manipul...]]></description><link>https://tomasalabes.me/convert-svg-to-raphael-in-one-step</link><guid isPermaLink="true">https://tomasalabes.me/convert-svg-to-raphael-in-one-step</guid><category><![CDATA[SVG]]></category><category><![CDATA[RaphaelJs]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Sun, 17 Feb 2013 12:30:16 GMT</pubDate><content:encoded><![CDATA[<p>Perhaps you have heard of the <a target="_blank" href="raphaeljs.com">Raphaël</a> library. Raphaël is a small JavaScript library that should simplify your work with vector graphics on the web. It's open-source and its one of the most famous libraries on github, the most popular for svg manipulation on the browser.</p>
<p>As the library wraps all svg elements into raphael objects, it wasn't posible at first to convert an svg file to those objects, and it was a really requested feature for the library.
Well, the author didn't add to the project but he did a tool for it, called rappar.</p>
<p>Here its an example of how to use it:
First of all you must have node installed.
Then you would download the official repo but it has a bug with the latest node version, so download mine which has the fix.
Now is time to convert your svg file, I took this svg as example:</p>
<p><img src="/blog/images/eagle.jpg" /></p>
<p>(pretty cool huh? you can find the free svg here)</p>
<p>Execute</p>
<pre><code class="lang-bash">node rappar.js path/to/eagle.svg
</code></pre>
<p>This will output the svg code, but perhaps we could do this in a cleaner way:</p>
<pre><code class="lang-bash">node rappar.js path/to/eagle.svg &gt; myCode.txt
</code></pre>
<p>Now you have it in a separate file. Want to add it to your web? Like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> paper = Raphael(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1600</span>, <span class="hljs-number">1600</span>); <span class="hljs-comment">//I'm using an arbitrary width and height</span>
paper.add(your_code)
</code></pre>
<p>And you are done! Easy right? Now you can add any svg file to your browser converting it with this tool. Check the raphael documentation for more info on the library.</p>
<p>Enjoy!</p>
]]></content:encoded></item><item><title><![CDATA[Using NodeJS oAuth module to communicate with Twitter REST API 1.1]]></title><description><![CDATA[Hi, lets see how to use the 'oauth' module in nodeJS, for getting information from the Twitter API.
You should start by installing the module:
$ npm install oauth

And add it to the package.json of your app:
"dependencies": {
    "express": "3.1.0",
...]]></description><link>https://tomasalabes.me/using-nodejs-oauth-module-to-communicate-with-twitter-rest-api-11</link><guid isPermaLink="true">https://tomasalabes.me/using-nodejs-oauth-module-to-communicate-with-twitter-rest-api-11</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Twitter]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Wed, 06 Feb 2013 12:30:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Zs5X1KnHUzw/upload/bf7f442a2e7ba5b27dff6fd1b2880c1f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hi, lets see how to use the 'oauth' module in nodeJS, for getting information from the Twitter API.</p>
<p>You should start by installing the module:</p>
<pre><code class="lang-bash">$ npm install oauth
</code></pre>
<p>And add it to the package.json of your app:</p>
<pre><code class="lang-javascript"><span class="hljs-string">"dependencies"</span>: {
    <span class="hljs-string">"express"</span>: <span class="hljs-string">"3.1.0"</span>,
    <span class="hljs-string">"ejs"</span>: <span class="hljs-string">"*"</span>,
    <span class="hljs-string">"oauth"</span>: <span class="hljs-string">"*"</span>
  }
</code></pre>
<p>Then, in the file where you will add the twitter retrieval logic, import the module:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'util'</span>);
<span class="hljs-keyword">var</span> OAuth = <span class="hljs-built_in">require</span>(<span class="hljs-string">'oauth'</span>).OAuth;
</code></pre>
<p>Once you created your app and got your data in https://dev.twitter.com/:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> oa = <span class="hljs-keyword">new</span> OAuth(<span class="hljs-string">"https://api.twitter.com/oauth/request_token"</span>,
    <span class="hljs-string">"https://api.twitter.com/oauth/access_token"</span>,
    <span class="hljs-string">"YOUR_CONSUMER_KEY"</span>,
    <span class="hljs-string">"YOUR_CONSUMER_SECRET"</span>,
    <span class="hljs-string">"1.0A"</span>,
    <span class="hljs-literal">null</span>,
    <span class="hljs-string">"HMAC-SHA1"</span>);

<span class="hljs-keyword">var</span> access_token = <span class="hljs-string">'YOUR_ACCESS_TOKEN'</span>;
<span class="hljs-keyword">var</span> access_token_secret = <span class="hljs-string">'YOUR_ACCESS_TOKEN_SECRET'</span>
</code></pre>
<p>Then I will give you a couple of examples of how to get stuff from Twitter:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">exports</span>.getLatestTweets = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">tweeter, count, callback</span>) </span>{
    oa.get(<span class="hljs-string">"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name="</span> + tweeter + <span class="hljs-string">"&amp;count="</span> + count, access_token, access_token_secret, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error, data</span>) </span>{
        <span class="hljs-keyword">var</span> result;
        <span class="hljs-keyword">if</span>(error){
            result = {<span class="hljs-attr">error</span>: error};
        }<span class="hljs-keyword">else</span>{
            result = data;
        }

        callback(result);
    });
};

<span class="hljs-built_in">exports</span>.getLatestProfilePicture = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">tweeter, callback</span>) </span>{
    oa.get(<span class="hljs-string">"http://api.twitter.com/1.1/users/show.json?screen_name="</span> + tweeter, access_token, access_token_secret, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error, data</span>) </span>{
        <span class="hljs-keyword">var</span> result;
        <span class="hljs-keyword">if</span>(error){
            result = {<span class="hljs-attr">error</span>: error};
        }<span class="hljs-keyword">else</span>{
            result = <span class="hljs-built_in">JSON</span>.parse(data);
        }

        callback(result);
    });
};
</code></pre>
<p>To use it, import it from other js</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> twitterUtil = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path/to/twitterUtil'</span>);
</code></pre>
<p>Now go get Twitter data and use it for good!!</p>
<p>Enjoy!</p>
]]></content:encoded></item><item><title><![CDATA[Turn off the lights! getUserMedia API experiment]]></title><description><![CDATA[Hi folks, 2nd post here :)
I've been getting to know the new HTML5 Web RTC project and the getUserMedia API through this great HTML5Rocks article by Eric Bidelman.
Don't know what Web RTC is? Quick definition from the projects Web:
"WebRTC is an open...]]></description><link>https://tomasalabes.me/turn-off-the-lights-getusermedia-api-experiment</link><guid isPermaLink="true">https://tomasalabes.me/turn-off-the-lights-getusermedia-api-experiment</guid><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Thu, 24 Jan 2013 12:30:16 GMT</pubDate><content:encoded><![CDATA[<p>Hi folks, 2nd post here :)</p>
<p>I've been getting to know the new HTML5 Web RTC project and the getUserMedia API through this great HTML5Rocks article by Eric Bidelman.</p>
<p>Don't know what Web RTC is? Quick definition from the projects Web:
"WebRTC is an open framework for the web that enables Real Time Communications in the browser. It includes the fundamental building blocks for high quality communications on the web such as network, audio and video components used in voice and video chat applications.
These components, when implemented in a browser, can be accessed through a Javascript API, enabling developers to easily implement their own RTC web app. "</p>
<p>The navigator.getUserMedia() API allows web apps to access a user's camera and microphone.</p>
<p>Playing around with the javascript API, I made a simple website where, through your webcam, you can take snapshots, add filters to them, and whenever you want (this is my new thing) turn off the camera by covering it with your hand (or whatever).
To show you what I mean, this is the web site.</p>
<p>I would like to show you how I did this, hope you enjoy it.
Boilerplate</p>
<p>First I downloaded the last html5 boilerplate, this gives all you need to get started.
In the template you will see this comment:</p>
<pre><code class="lang-javascript">&lt;!-- Add your site or application content here --&gt;
</code></pre>
<p>There is where you start adding things. The first html element you need now is the following:</p>
<pre><code class="lang-javascript">&lt;video autoplay=<span class="hljs-string">""</span>&gt;&lt;/video&gt;
</code></pre>
<p>This tag will be where the camera will stream its content.
Feature Detection</p>
<p>Then, following Eric's article, I started the feature detection and asking permission for the video.
"The getUserMedia() API is still very new. In Chrome &lt; 21, you need to enable the feature by visiting about:flags. If you're using Chrome 21, you can skip this section."
You can see other browsers compatibility with this feature here.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.URL = <span class="hljs-built_in">window</span>.URL || <span class="hljs-built_in">window</span>.webkitURL;
navigator.getUserMedia  = navigator.getUserMedia || navigator.webkitGetUserMedia ||
                          navigator.mozGetUserMedia || navigator.msGetUserMedia;

<span class="hljs-keyword">var</span> video = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'video'</span>),
    localMediaStream;

<span class="hljs-keyword">if</span> (navigator.getUserMedia) {
  navigator.getUserMedia({<span class="hljs-attr">video</span>: <span class="hljs-literal">true</span>}, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">stream</span>) </span>{
    video.src = <span class="hljs-built_in">window</span>.URL.createObjectURL(stream);
    localMediaStream = stream;
  }, onFailSoHard);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">//You can add a fallback here if you want, I didn't.</span>
  <span class="hljs-comment">//video.src = 'somevideo.webm';</span>
}
</code></pre>
<p>Notice that you can use 'audio: true' also in the first parameter of the getUserMedia() function, but it isn't necessary as we only want to take photos or analyze images.</p>
<p>I'm only going to explain the part about covering the webcam, as the filters part is well explained in the html5rocks article.</p>
<p>First, taking frames snapshots</p>
<p>To do this you must add a canvas element to the html:</p>
<pre><code class="lang-javascript">&lt;canvas id=<span class="hljs-string">"ghostCanvas"</span> style=<span class="hljs-string">"display:none"</span> width=<span class="hljs-string">"440"</span> height=<span class="hljs-string">"320"</span>&gt;&lt;/canvas&gt;
</code></pre>
<p>This canvas will be one where our images will be taken secretly, the width/height can be anything you want.</p>
<p>How do we take a screenshot of the camera? Here:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">snapshot</span>(<span class="hljs-params">canvas</span>) </span>{
    <span class="hljs-keyword">if</span> (localMediaStream) {
        <span class="hljs-keyword">var</span> canvasContext = canvas.getContext(<span class="hljs-string">'2d'</span>);
        canvasContext.drawImage(video, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">440</span>, <span class="hljs-number">320</span>);
    }
}
</code></pre>
<p>You can see the drawImage function here, but the parameters can be easily understood with this image:</p>
<p>Analyzing the images</p>
<p>To analyze the images I used a very simple algorithm, comparing 9 points of the images, this ones:</p>
<p>This is how:</p>
<pre><code class="lang-javascript">    darkyImage: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">canvas</span>) </span>{
        <span class="hljs-keyword">var</span> canvasContext = canvas.getContext(<span class="hljs-string">'2d'</span>),
            i, j,
            x, y,
            image, data;

        <span class="hljs-keyword">for</span> (i = <span class="hljs-number">1</span>; i &lt; <span class="hljs-number">3</span>; i++) {
            <span class="hljs-keyword">for</span> (j = <span class="hljs-number">1</span>; j &lt; <span class="hljs-number">3</span>; j++) {
                x = canvas.width / j - <span class="hljs-number">1</span>;
                y = canvas.height / i - <span class="hljs-number">1</span>;
                image = canvasContext.getImageData(x, y, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
                data = image.data;
                <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">this</span>.darkyPixel(data)) {
                    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
                }
            }
        }
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
</code></pre>
<p>What about that 'darkyPixel' function? Simple (really, VERY simple), I chose a color limit (20) and a redOffset, this offset is because as your palm has a reddish color, the red part of the pixel generally was 20/25 points higher, so this adjustment did the analysis a bit better.</p>
<pre><code class="lang-javascript">darkyPixel: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">rgba</span>) </span>{
        <span class="hljs-keyword">var</span> offColor = <span class="hljs-number">20</span>,
            redOffset = <span class="hljs-number">25</span>;
        <span class="hljs-keyword">return</span> ((rgba[<span class="hljs-number">0</span>] &lt; offColor + redOffset &amp;&amp; rgba[<span class="hljs-number">1</span>] &lt; offColor &amp;&amp; rgba[<span class="hljs-number">2</span>] &lt; offColor));
</code></pre>
<p>Of course any algorithm you would like to suggest is welcome!
Reading the camera</p>
<p>Now, when the user accepts us to use their camera, we need to start reading the camera taking snapshots every N seconds/ms, I choose 700ms.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">startReading</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">var</span> ghostCanvas = $(<span class="hljs-string">'#ghostCanvas'</span>)[<span class="hljs-number">0</span>];
        <span class="hljs-built_in">setInterval</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
            snapshot(ghostCanvas);
            <span class="hljs-keyword">if</span> (darkyImage(ghostCanvas)) {
                stopWebCam();
            }
        }, <span class="hljs-number">700</span>);
    }
</code></pre>
<p>This should be inside the navigator.getUserMedia(), like this:</p>
<pre><code class="lang-javascript"> navigator.getUserMedia({<span class="hljs-attr">video</span>: <span class="hljs-literal">true</span>}, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">stream</span>) </span>{
    video.src = <span class="hljs-built_in">window</span>.URL.createObjectURL(stream);
    localMediaStream = stream;
    startReading(); <span class="hljs-comment">//here!!</span>
  }, onFailSoHard);
</code></pre>
<p>How do I turn off the service when you cover the camera?
You covered the webcam! Shut it down!</p>
<pre><code class="lang-javascript">    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stopWebCam</span>(<span class="hljs-params"></span>)</span>{
        video.pause();
        localMediaStream.stop();
        $(<span class="hljs-string">'video'</span>).fadeOut(<span class="hljs-number">500</span>);
        $(<span class="hljs-string">"#ghostCanvas"</span>).hide();
    }
</code></pre>
<p>Well, that's it!
Here it is all together:</p>
<pre><code class="lang-javascript">$(<span class="hljs-built_in">document</span>).ready(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">window</span>.URL = <span class="hljs-built_in">window</span>.URL || <span class="hljs-built_in">window</span>.webkitURL;

    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia || navigator.msGetUserMedia;

    <span class="hljs-keyword">var</span> onFailSoHard = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Reeeejected!'</span>, e);
    };

    <span class="hljs-keyword">var</span> video = $(<span class="hljs-string">'video'</span>)[<span class="hljs-number">0</span>];
    <span class="hljs-keyword">var</span> canvas = $(<span class="hljs-string">'canvas'</span>)[<span class="hljs-number">0</span>];
    <span class="hljs-keyword">var</span> localMediaStream = <span class="hljs-literal">null</span>;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stopWebCam</span>(<span class="hljs-params"></span>)</span>{
        video.pause();
        localMediaStream.stop();
        $(<span class="hljs-string">'video'</span>).fadeOut(<span class="hljs-number">1000</span>);
        $(<span class="hljs-string">"#ghostCanvas"</span>).hide();
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">snapshot</span>(<span class="hljs-params">canvas</span>) </span>{
        <span class="hljs-keyword">if</span> (localMediaStream) {
            <span class="hljs-keyword">var</span> canvasContext = canvas.getContext(<span class="hljs-string">'2d'</span>);
            canvasContext.drawImage(video, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">440</span>, <span class="hljs-number">320</span>);
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">startReading</span>(<span class="hljs-params"></span>)</span>{
        <span class="hljs-keyword">var</span> ghostCanvas = $(<span class="hljs-string">'#ghostCanvas'</span>)[<span class="hljs-number">0</span>];
        <span class="hljs-keyword">var</span> intervalId = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
            snapshot(ghostCanvas);
            <span class="hljs-keyword">if</span> (darkyImage(ghostCanvas)) {
                stopWebCam();
            }
        }, <span class="hljs-number">1000</span>);
    }

    <span class="hljs-attr">darkyPixel</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">rgba</span>) </span>{
        <span class="hljs-keyword">var</span> offColor = <span class="hljs-number">20</span>,
            redOffset = <span class="hljs-number">25</span>;
        <span class="hljs-keyword">return</span> ((rgba[<span class="hljs-number">0</span>] &lt; offColor + redOffset &amp;&amp; rgba[<span class="hljs-number">1</span>] &lt; offColor &amp;&amp; rgba[<span class="hljs-number">2</span>] &lt; offColor));

    darkyImage: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">canvas</span>) </span>{
        <span class="hljs-keyword">var</span> canvasContext = canvas.getContext(<span class="hljs-string">'2d'</span>),
            i, j,
            x, y,
            image, data;

        <span class="hljs-keyword">for</span> (i = <span class="hljs-number">1</span>; i &lt; <span class="hljs-number">3</span>; i++) {
            <span class="hljs-keyword">for</span> (j = <span class="hljs-number">1</span>; j &lt; <span class="hljs-number">3</span>; j++) {
                x = canvas.width / j - <span class="hljs-number">1</span>;
                y = canvas.height / i - <span class="hljs-number">1</span>;
                image = canvasContext.getImageData(x, y, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
                data = image.data;
                <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">this</span>.darkyPixel(data)) {
                    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
                }
            }
        }
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }

    <span class="hljs-keyword">if</span> (navigator.getUserMedia) {
        navigator.getUserMedia({<span class="hljs-attr">video</span>: <span class="hljs-literal">true</span>}, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">stream</span>) </span>{
            video.src = <span class="hljs-built_in">window</span>.URL.createObjectURL(stream);

            localMediaStream = stream;
            startReading();

        }, onFailSoHard);
    } <span class="hljs-keyword">else</span> {
        alert(<span class="hljs-string">'getUserMedia() is not supported in your browser'</span>);
    }
});
</code></pre>
<p>I know that my site has a couple of more things like modules and dimming the background while covering the webcam but I'll try to make another post with them.</p>
<p>Here is my github repo with my web site source code.</p>
<p>Enjoy!</p>
]]></content:encoded></item><item><title><![CDATA[Palette behaviour with RaphaelJS]]></title><description><![CDATA[Hi all, welcome to my new blog!
For my first entry I chose RaphaelJS, an svg library to manipulate SVG with javascript in a easier way than directly with the SVG DOM, but of course losing some of the svg spec capabilities.
I've been working with Raph...]]></description><link>https://tomasalabes.me/palette-behaviour-with-raphaeljs</link><guid isPermaLink="true">https://tomasalabes.me/palette-behaviour-with-raphaeljs</guid><category><![CDATA[RaphaelJs]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Sat, 03 Nov 2012 12:30:16 GMT</pubDate><content:encoded><![CDATA[<p>Hi all, welcome to my new blog!
For my first entry I chose <a target="_blank" href="raphaeljs.com">RaphaelJS</a>, an svg library to manipulate SVG with javascript in a easier way than directly with the SVG DOM, but of course losing some of the svg spec capabilities.
I've been working with Raphaeljs for a while now and I would like to share some code with you for a nice behaviour, the palette behaviour.</p>
<p>First of all, in what consists my palette behaviour? It's like in many editors, where you have elements on the side that you can add by drag and drop to a 'canvas'.</p>
<p>I will assume that we already have the rectangle representing the palette and the elements inside, and I will explain to you how to give them the correct behaviour.
For this we will use the drag() function that Raphael gives us, using some functions that give us the feeling of d&amp;d new elements to a canvas.</p>
<p>You'll have to add to every palette element this startFunction:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//DragFunctions is the object that has all the 3 d&amp;d methods, clearer in the complete file</span>
<span class="hljs-attr">paletteStart</span>:<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// keep the relative coords at the start of the drag</span>
    <span class="hljs-built_in">this</span>.ox = <span class="hljs-number">0</span>;
    <span class="hljs-built_in">this</span>.oy = <span class="hljs-number">0</span>;

    <span class="hljs-comment">// as we are dragging the palette element, we clone it to leave one in his place.</span>
    <span class="hljs-keyword">var</span> newPaletteObj = <span class="hljs-built_in">this</span>.clone();

    <span class="hljs-comment">//we give the new palette element the behaviour of a palette element</span>
    DragFunctions.addDragAndDropCapabilityToPaletteOption(newPaletteObj);

    <span class="hljs-comment">//nice animation</span>
    <span class="hljs-built_in">this</span>.animate({<span class="hljs-string">"opacity"</span>:<span class="hljs-number">0.5</span>}, <span class="hljs-number">500</span>);
}
</code></pre>
<p>Now we need the function while the element is being dragged:</p>
<pre><code class="lang-javascript">move: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">dx, dy</span>) </span>{
    <span class="hljs-comment">// calculate translation coords</span>
    <span class="hljs-keyword">var</span> new_x = dx - <span class="hljs-built_in">this</span>.ox;
    <span class="hljs-keyword">var</span> new_y = dy - <span class="hljs-built_in">this</span>.oy;

    <span class="hljs-comment">// transforming coordinates</span>
    <span class="hljs-built_in">this</span>.transform(<span class="hljs-string">'...T'</span> + new_x + <span class="hljs-string">','</span> + new_y);

    <span class="hljs-comment">// save the new values for future drags</span>
    <span class="hljs-built_in">this</span>.ox = dx;
    <span class="hljs-built_in">this</span>.oy = dy;
}
</code></pre>
<p>And finally, the function executed at finish dropping:</p>
<pre><code class="lang-javascript">paletteUp: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">if</span>(!DragFunctions.isInsideCanvas(<span class="hljs-built_in">this</span>)){
        <span class="hljs-built_in">this</span>.remove();
        <span class="hljs-comment">//notify the user as you want!</span>
    }<span class="hljs-keyword">else</span>{
        <span class="hljs-comment">//Giving the new D&amp;D behaviour</span>
        <span class="hljs-built_in">this</span>.undrag();

        <span class="hljs-comment">//give the element the new d&amp;d functionality!</span>

        <span class="hljs-built_in">this</span>.animate({<span class="hljs-string">"opacity"</span>:<span class="hljs-number">1</span>}, <span class="hljs-number">500</span>);
    }
}
</code></pre>
<p>2 things to comment here, when the element is dropped, you will have to remove the palette behaviour and give it another one (a plain d&amp;d functionality), if not, it will continue cloning elements all around.
Here I give you some nice behaviour to give them:</p>
<pre><code class="lang-javascript">start:<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// keep the relative coords at the start of the drag</span>
    <span class="hljs-built_in">this</span>.ox = <span class="hljs-number">0</span>;
    <span class="hljs-built_in">this</span>.oy = <span class="hljs-number">0</span>;
    <span class="hljs-comment">// animate attributes to a "being dragged" state</span>
    <span class="hljs-built_in">this</span>.animate({<span class="hljs-string">"opacity"</span>:<span class="hljs-number">0.5</span>}, <span class="hljs-number">500</span>);
},
    <span class="hljs-comment">//same move function</span>
    <span class="hljs-attr">up</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">if</span>(!DragFunctions.isInsideCanvas(<span class="hljs-built_in">this</span>)){
            <span class="hljs-built_in">this</span>.animate({<span class="hljs-attr">transform</span>:<span class="hljs-string">'...T'</span> + (-<span class="hljs-built_in">this</span>.ox) + <span class="hljs-string">','</span> + (-<span class="hljs-built_in">this</span>.oy)}, <span class="hljs-number">1000</span>, <span class="hljs-string">"bounce"</span>);
        }
        <span class="hljs-built_in">this</span>.animate({<span class="hljs-string">"opacity"</span>: <span class="hljs-number">1</span>}, <span class="hljs-number">500</span>);
    },

    <span class="hljs-comment">//and the method that gives the behaviour</span>
    <span class="hljs-attr">addDragAndDropCapabilityToSet</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">compSet</span>) </span>{
        compSet.drag(<span class="hljs-built_in">this</span>.move, <span class="hljs-built_in">this</span>.start, <span class="hljs-built_in">this</span>.up, compSet, compSet, compSet);
    }
</code></pre>
<p>And as you may also see, we have a validator that sees if the element is inside the canvas, it is a very useful function, here:</p>
<pre><code class="lang-javascript">isInsideCanvas: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">obj</span>)</span>{
            <span class="hljs-keyword">var</span> canvasBBox = <span class="hljs-comment">//get your 'canvas'</span>
            <span class="hljs-keyword">var</span> objectBBox = obj.getBBox();
            <span class="hljs-keyword">var</span> objectPartiallyOutside = !Raphael.isPointInsideBBox(canvasBBox, objectBBox.x, objectBBox.y) || !Raphael.isPointInsideBBox(canvasBBox, objectBBox.x, objectBBox.y2) || !Raphael.isPointInsideBBox(canvasBBox, objectBBox.x2, objectBBox.y) || !Raphael.isPointInsideBBox(canvasBBox, objectBBox.x2, objectBBox.y2);
            <span class="hljs-keyword">return</span> !(objectPartiallyOutside);
        }
</code></pre>
<p>Finally, the place to call to give the element all this behaviour:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//this works for elements and sets</span>
<span class="hljs-attr">addDragAndDropCapabilityToPaletteOption</span>:<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">compSet</span>) </span>{
    compSet.drag(<span class="hljs-built_in">this</span>.move, <span class="hljs-built_in">this</span>.paletteStart, <span class="hljs-built_in">this</span>.paletteUp, compSet, compSet, compSet);
}
</code></pre>
<p>A demo of this is in a website I created to play with raphael, called comoformamos project
The hole code is in a github gist or hosted on github so if you want to get a little deeper in the code feel free to do it.</p>
<p>I hope you find this helpful,
til next time!</p>
]]></content:encoded></item><item><title><![CDATA[Testing in Agile Teams]]></title><description><![CDATA[I have just read this book: Agile Testing: A Practical Guide for Testers and Agile Teams by Lisa Crispin and Janet Gregory, and I would like to share this presentation I've given at work about it.
From the book description:
Testing is a key component...]]></description><link>https://tomasalabes.me/testing-in-agile-teams</link><guid isPermaLink="true">https://tomasalabes.me/testing-in-agile-teams</guid><category><![CDATA[agile]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Tomas Alabes]]></dc:creator><pubDate>Thu, 16 Feb 2012 12:30:16 GMT</pubDate><content:encoded><![CDATA[<p>I have just read this book: Agile Testing: A Practical Guide for Testers and Agile Teams by Lisa Crispin and Janet Gregory, and I would like to share this presentation I've given at work about it.</p>
<p>From the book description:</p>
<p>Testing is a key component of agile development. The widespread adoption of agile methods has brought the need for effective testing into the limelight, and agile projects have transformed the role of testers. Much of a tester’s function, however, remains largely misunderstood. What is the true role of a tester? Do agile teams actually need members with QA backgrounds? What does it really mean to be an “agile tester?”
[...] In Agile Testing, Crispin and Gregory define agile testing and illustrate the tester’s role with examples from real agile teams. They teach you how to use the agile testing quadrants to identify what testing is needed, who should do it, and what tools might help. The book chronicles an agile software development iteration from the viewpoint of a tester and explains the seven key success factors of agile testing.</p>
<p>As a developer is really helpful to know the point of view of agile members whose mainly job is  testing and worrying about the product internal and external quality.
I recommend it.
"Quality is not negotiable."</p>
<iframe height="421" src="http://www.slideshare.net/slideshow/embed_code/15977357" style="border-width:1px 1px 0;border:1px solid #CCC;margin-bottom:5px" width="512"> </iframe>

<p>Agile testing from Tomas Alabes</p>
]]></content:encoded></item></channel></rss>