<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yazeed Obaid on Medium]]></title>
        <description><![CDATA[Stories by Yazeed Obaid on Medium]]></description>
        <link>https://medium.com/@yazeedobaid?source=rss-a8cee96ce60a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*N-xI26Vte5ZS1aLv.jpg</url>
            <title>Stories by Yazeed Obaid on Medium</title>
            <link>https://medium.com/@yazeedobaid?source=rss-a8cee96ce60a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 22:56:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yazeedobaid/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why We Struggle to Get Good Results Even Though we’re Speaking the Same Language]]></title>
            <link>https://medium.com/@yazeedobaid/why-we-struggle-to-get-good-results-even-though-were-speaking-the-same-language-413913ad69dc?source=rss-a8cee96ce60a------2</link>
            <guid isPermaLink="false">https://medium.com/p/413913ad69dc</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[writing-prompts]]></category>
            <dc:creator><![CDATA[Yazeed Obaid]]></dc:creator>
            <pubDate>Thu, 30 Oct 2025 16:34:43 GMT</pubDate>
            <atom:updated>2025-10-30T16:34:43.055Z</atom:updated>
            <content:encoded><![CDATA[<h3>Author’s Note</h3><p><em>This article will not introduce solutions, or provide instructions on how to write prompts for AI tools. it is more shedding light on why we get some results that are not what we expect (in some cases). This article reflects author’s opinions. Not biased towards any particular AI tool.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aF4Vn9goI7ZvOM_9x1PiEQ.png" /><figcaption>Credits goes to ChatGPT. Featured image for this article. Why we Struggle to Get Good Results Even Though we’re Speaking the Same Language</figcaption></figure><p>While I was learning about Large Language Models (LLMs) and tokenization specifically, I asked an AI agent to explain tokens to me. And this sentence in one of its responses caught my attention and is the reason for writing this article:</p><blockquote><em>“This is why I generate left-to-right and can’t “plan ahead” the way humans might when writing.”</em></blockquote><p>Think about that sentence for a second. What does that mean ?! We human write text left-to-right (and right-to-left in other languages, but point here is that, we start from one direction to another).</p><p>The key phrase to focus on here is “plan ahead”. When we human write text, a lot of thoughts are active in our heads at that time. Why we are writing, towards what goal, what we will include, main key points, writing about past events, etc. But an LLM doesn’t work like that. That is what I have discovered and wanted to share in this article. This may shed the light on how LLMs work and can unlock the potential to construct good prompts that will direct LLMs towards the end goal we intended to achieve.</p><h3>The Fundamental Difference: How Humans and LLMs Process Language</h3><p>Starting from what triggers the sentence above. Tokenization. So an LLM first tokenizes our prompt into tokens. A token can be a complete word, half a word, multiple words, this depends on algorithm used for tokenization. Next, tokens are converted into numbers, embeddings vectors, then these vectors are passed into a pipeline of neural networks, transformer layers, etc. Finally, LLMs convert back generated response tokens into text and it is displayed to us.</p><p>In the above paragraph I explained in a very very high level way, how an LLM works. But how does that relates to the sentence above ? The relation is on how an LLM processes our response. LLMs do plan ahead, but they don’t plan exactly like what I or you wanted it to, or think it will do. Because they don’t have our thoughts, experience, full intention, overlapping ideas, our global end goal(s), and thinking mindset.</p><p>As a result, in the majority of responses we get from AI agent tools, results are not like what we wanted, to some degree of course. This is noticeable when requesting an LLM to generate code. Programming languages are very well structured and deterministic languages. But even thought, they fail to generate results that we think we will get.</p><p>I have dug deeper into the above sentence and why things are like that. From the research I did and hands-on experience of using LLMs, I found the following behaviors that are related to the sentence above and explains why I have been getting responses that not what I wanted as a software engineer who works with code (the language I and LLM speaks):</p><h4>The Commitment Lock-in Problem</h4><p>LLMs cannot change/revise a token once it is generated per response. So, when an LLM generate a token as part of a response and it turns out that it is wrong, it cannot go back and change it. It is fixed. This explains why in some cases, text writing of an LLM doesn’t make sense. Because they cannot go back and update it. Just to clarify, here we are talking about commitment in a single response session. Not during a complete conversation.</p><p>Commitment in early stages lead LLMs when generating text to commit to a plan, and they cannot change it later even if it was better to change it. For example, if we asked an LLM to generate a list of places to visit in a city. They start thinking and then decide that I will give 5 places. Hence, it has committed itself with 5 places. Even if it generated 5 then encounter another one that is better than them, they don’t include it. Because they have committed to exactly 5 things. Or worst, what if they cannot find the fifth one! Then in some cases it will start to diverge and loose the attention.</p><h4>Loss of Global Coherence</h4><p>LLMs cannot keep maintaining a long global goal. They will diverge from it for different reasons, including long context, memory becoming full, attention is lost due to long context, etc. Also, not defining an end goal when asking an LLM will lead to this, as it cannot know what is the end result. Hence, the end goal should be planned, explained, and steered to.</p><p>I think of training data for an LLM like past experiences for us. But the twist here is that, training data combines past experiences of way too many individuals. Hence, maintaining a coherent narrative (or goal) will be the challenge for an LLM. This leads us to the next point.</p><h4>Pattern Matching vs. Contextual Style</h4><p>LLMs use different ways to overcome the behaviors mentioned above. But these ways also cause side effects. LLMs rely heavily on training data and patterns they have seen in training data. As they will try to probabilistically plan based on that and by pattern matching. Now this affects programming and writing code heavily. Because not all code is written the same way. Even if it tries to follow design patterns.</p><p>Codebases always have patterns written by teams working on them. In this case, the patterns that LLM should follow is the codebase patterns in the first place, not patterns from training data. And to me, I like to extend that to bullet proof-design patterns as well. To me, if the code will be easier to read and maintain by breaking a design pattern that will introduce abstractions. Then so be it. I know a saying that applies very well to this case:</p><blockquote>Simplicity Favors Regularity</blockquote><p>In programming and codebases. Simplicity is to follow patterns in a codebase by agreement between individuals who are working on it. And if those patterns are followed correctly, they will become the regularity.</p><p>Now back to LLMs. Imagine a team of 10 developers, if they don’t agree on a well-defined structure and patterns, then reading and maintaining that codebase would be very difficult as developers will be switching context and different mindsets. If this is the case of the developers who are working on that codebase. Then imagine what will happen to an LLM.</p><p>Let’s worsen this even more. What if the codebase is using libraries that are unknown or not very common (not that much of sample code snippets, tips and tricks, discussions, poor documentation, etc.). The LLM will start hallucinate and generate nonsensed results.</p><p>In a project that I was working on recently. The project was written fully without test cases. And it is utilizing libraries that are not very common. The project domain is Dynamics CRM. Hence, it is a closed small community. I thought about using an AI agent to generate test cases for that project. I started by give it a simple prompt like:</p><pre>Generate test cases for this class</pre><p>But the results were very poor. Then I did the following, I defined a testing guideline file and practices that we follow when writing test cases. But I didn’t get very detailed, especially on the testing library that we are using. That library is not very known or have good documentation.</p><p>The result was very complex test cases that rely heavily on mocking. Which makes sense at the first place. Because, if we are writing tests and we couldn’t inject dependencies or replace them with faked ones to simulate a specific behavior. Then mocking is the first thing that comes to mind. Instead of mocking, the library offers ways for testing that don’t rely on mocking. But these ways sadly are not very well documented. And in instructions I didn’t explain or steered it to find ways instead of mocking.</p><p>Now, zooming out on this subject, what if a codebase includes dozens of libraries like this one — little code snippet on the internet, poor documentation, hidden tips and tricks, etc. Combine that with coding styles and patterns that are specific to that codebase. The LLM will hit a brick wall, and start hallucinating, and using patterns that are way far from codebase and its standards.</p><p>Let’s look next to a case study that will illustrate the points above and the sentence we started this article with:</p><h3>Case Study: How LLMs Write Detective Stories</h3><p>To illustrate the above behaviors, we can compare how humans write detective or mysterious stories compared to when we ask LLMs to do that.</p><ul><li>For humans, they start from the ending or near the ending, the main actors, the main scenes’, etc. <em>I’m not a story writer, but this is how I’d approach it.</em> Hence, the plot will be thought of at first, before assembling anything else.</li><li>For an LLM (if we don’t give it the plot or any details), it starts by generating text, one at a time, and adjusting what it generates based on past generated text (hence commitment and fixed generation), starts planning for plot and ending by already written text (no end goal). Feels like an optimization problem! I have these details beforehand, now generate a plot and an ending that goes along with what have been generated (pattern matching).</li></ul><p>I have asked an AI agent to generate a detective story of maximum 2 paragraphs, and then asked it how it generated and thought about it step by step. Here is the conversation:</p><pre>## Prompt:<br>write me a detective story, 2 paragraphs max<br><br><br>## Response:<br>Detective Marina Chen stood in the locked study, staring at the impossible <br>scene: millionaire Marcus Whitfield dead at his desk, a knife in his back, <br>yet the room had been locked from the inside with no other way in or out. <br>The windows were sealed, the chimney too narrow for a person, and the key <br>was still in Whitfield&#39;s pocket. His three children—each with millions to <br>gain—had alibis placing them in different cities. But something nagged at <br>Chen as she examined the antique grandfather clock that had stopped at <br>3:17 AM, its pendulum still swinging despite showing the wrong time <br>entirely: 8:43.<br><br>The revelation hit when she noticed the nearly invisible fishing line <br>tangled in the clock&#39;s mechanism. The killer had rigged an elaborate <br>device: the knife was spring-loaded above the door, triggered by a timer <br>connected to the grandfather clock. Whitfield himself had unknowingly <br>activated it when he&#39;d entered the study at 3:17 AM and locked the door <br>behind him, the mechanism using the door&#39;s motion to wind the spring. <br>The clock had two faces—one visible, one hidden inside—explaining the <br>time discrepancy. The culprit? The eldest son, an engineer who&#39;d &quot;gifted&quot; <br>his father the restored clock weeks earlier, knowing his father&#39;s rigid <br>routine of checking his overseas investments every night at exactly <br>the same time. His alibi in Tokyo meant nothing; the murder weapon had <br>been patiently waiting for weeks.<br><br><br>## Prompt:<br>walk me through the steps on how u generated this story. From beginning, <br>to actors, to scenes, to ending, to murderer ?<br><br><br>## Response:<br>Here&#39;s how I built that detective story step-by-step:<br><br>## 1. **Started with the Classic Setup**<br>I knew I needed a &quot;locked room mystery&quot; - it&#39;s a detective story staple <br>that immediately creates intrigue. The challenge: someone is dead in a <br>room that seems impossible to enter or exit.<br><br>## 2. **Created the Victim**<br>Marcus Whitfield - I made him a millionaire because:<br>- Rich people have more potential enemies<br>- Inheritance provides clear motive<br>- His wealth could justify having a private locked study<br><br>## 3. **Chose the Detective**<br>Marina Chen - I wanted a professional investigator (not amateur sleuth) <br>and picked a name that felt modern and competent without being cliché.<br><br>## 4. **Established the &quot;Impossible&quot; Crime Scene**<br>- Knife in the back (can&#39;t be suicide)<br>- Room locked from inside<br>- Key still in victim&#39;s pocket<br>- Windows sealed, chimney too narrow<br>- This creates the &quot;how could anyone do this?&quot; puzzle<br><br>## 5. **Added Red Herrings and Clues**<br>- Three children with inheritance motives (classic suspicion pool)<br>- All have alibis in different cities (seeming impossibility)<br>- The grandfather clock with two different times - this became my key clue<br><br>## 6. **Worked Backward from the Solution**<br>I decided on a mechanical/delayed murder because:<br>- It solves the locked room problem<br>- It breaks the alibi problem<br>- The fishing line and clock mechanism felt clever but plausible<br>- The spring-loaded trap triggered by the victim himself adds irony<br><br>## 7. **Made the Killer and Motive Make Sense**<br>The eldest son as engineer explains:<br>- How he had the skills to build it<br>- Why he could gift the clock without suspicion<br>- The weeks of patience showed premeditation<br>- Tokyo alibi emphasized how &quot;perfect&quot; his plan seemed<br><br>The story flowed from establishing impossibility → providing subtle <br>clues → revealing an ingenious solution.<br><br><br><br>## Prompt:<br>So when u put the story, u didn&#39;t think at ending from start ? Or the <br>murderer to be one of his sons. Because it could be his servant as he <br>is rich<br><br><br>## Response:<br>You&#39;re absolutely right - I didn&#39;t have the ending fully planned from <br>the start! Here&#39;s how it actually evolved:<br><br>## **What I Started With:**<br>- Knew it would be a locked room mystery (that&#39;s a classic format)<br>- Knew someone rich would be dead (more plot possibilities)<br>- That&#39;s about it!<br><br>## **What Developed As I Wrote:**<br><br>**Paragraph 1:** While writing, I added the three children with alibis <br>somewhat automatically - it&#39;s such a common trope. But you&#39;re right, <br>I could have gone with:<br>- A servant (classic &quot;butler did it&quot;)<br>- A business partner (betrayal angle)<br>- A spouse (crime of passion)<br>- Even suicide staged to frame someone<br><br>**The Clock Detail:** When I wrote about the grandfather clock showing <br>two different times, I didn&#39;t initially know exactly why - I just knew <br>it would be important. It felt like a good mysterious detail.<br><br>**Paragraph 2:** Only when I got to the solution did I decide:<br>- Make it mechanical (to solve the locked room)<br>- Pick the eldest son specifically<br>- Make him an engineer (to justify the technical knowledge)<br><br>## **Why I Unconsciously Chose the Son:**<br>Looking back, I think I gravitated toward the inheritance/family angle <br>because:<br>- It&#39;s emotionally compelling (family betrayal)<br>- The &quot;gift from son&quot; has nice dramatic irony<br>- Engineer son was an efficient way to explain the technical skill<br><br>But you&#39;re totally right - a servant who&#39;d been stealing and needed to <br>cover it up, or who&#39;d been mistreated for years, could have been equally <br>compelling. Or even a business rival who hired someone to plant the device!<br><br>The story definitely assembled itself as I wrote rather than being fully <br>planned - the ending crystallized only when I needed to solve the puzzle <br>I&#39;d created.</pre><h3>The Open Prompt Problem</h3><p>LLMs used the information given to it and when it couldn’t determine what to do or what path to follow, it starts to use its best guess. That is the core functionality of an LLM, matching and probability. At the end, LLMs uses numbers, probability, and matching patterns to decide and generate. If we get back to the testing example above, and we wanted to use the following prompt:</p><pre>I have these classes in order directory, I want you to generate <br>test cases for them</pre><p>Now, the above prompt is way too open. Think of these possibilities:</p><ol><li>What if one (or more) class(es) contains a request to an external API. How it will handle it ? From my experiments, it will not, test will reach that code and hit the API.</li><li>What is writing style it should follow ? Where to put these test files ? etc.</li><li>How to generate sample data for these classes ? and what defines a good sample data ?</li></ol><p>And many more things that will an LLM encounter and starts to decide on. Each decision made cannot be undone in a single response. Hence, some decisions at early stages can limit what next decisions can be. This is like having an open space to explore. But each step you take will limit the possible paths you can follow. Hence, The open space will become narrower at each step taken.</p><p>On the other hand, what if we thought of this from a developer point of view. How will a developer approach this task:</p><ol><li>Will examine what testing framework is being used. If not any is used then he/she needs to decide what framework to use and install/setup it.</li><li>Where to put the testing files ?</li><li>What is the writing style for the test cases ? Are we writing unit tests, integration tests, feature tests, end-to-end tests (call them whatever you want). But that needs to be decided.</li><li>Read the classes themselves to extract test cases and know what features/patterns they use. Do they need setup data ? What defines a good data and a bad data ? Do they need external API calls and how are we going to handle them ? Mocking ? Do we have a staging/testing endpoint instead of production one to hit ? Are we going to hit external API from start or replace it with a mock or faked implementation ?</li></ol><p>And more things that depends on the classes in question. But these are general points that repeats every time test cases need to be written.</p><p>As a result, giving an open prompt will open many exploration paths for an LLM. But that is not what we want (at least not every time). Constraints must be put in place when we want deterministic results. Hence, in some cases, when writing a prompt for an LLM, we need to think about it from point of view if we are going to implement it. Imagining at least the main stages that we need to reach and what decision to take at each stage. So that we are steering it to correct goal.</p><h3>Side Note</h3><p>Funny store when I asked the AI agent about planning ahead, it ended its response with this:</p><pre>### The Deep Irony<br>Here&#39;s what&#39;s mind-bending: I&#39;m explaining my own inability to <br>plan ahead... in a well-structured explanation that seems planned! <br>This works because:<br><br>* My training included millions of well-structured explanations<br>* The patterns of coherent exposition are baked into my weights<br>* I&#39;m following learned templates without explicit planning<br><br>It&#39;s like a jazz musician who can&#39;t hear ahead but has internalized <br>musical patterns so deeply they can improvise coherently anyway!</pre><h3>References</h3><ul><li><a href="https://en.wikipedia.org/wiki/Large_language_model">Large language model</a></li><li><a href="https://en.wikipedia.org/wiki/Large_language_model#Tokenization">Tokenization</a></li><li><a href="https://en.wikipedia.org/wiki/Word_embedding">Word embedding</a></li><li><a href="https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi">3Blue1Brown’s Neural networks playlist</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=413913ad69dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel Lumen with Multiple .env Files]]></title>
            <link>https://medium.com/@yazeedobaid/laravel-lumen-with-multiple-env-files-207380a06f16?source=rss-a8cee96ce60a------2</link>
            <guid isPermaLink="false">https://medium.com/p/207380a06f16</guid>
            <category><![CDATA[lumen]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[dotenv]]></category>
            <dc:creator><![CDATA[Yazeed Obaid]]></dc:creator>
            <pubDate>Thu, 21 Nov 2019 19:06:47 GMT</pubDate>
            <atom:updated>2019-11-21T19:06:47.716Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WjCdDGiykJ7JGcTwsknmfg.png" /></figure><h3>Laravel Lumen with Multiple .env Files</h3><p>Laravel’s .env has an APP_ENV variable that determine the environment of the application. The possible values for that variable are: <em>local</em>, <em>testing </em>and <em>production</em>. The file is used in the three environments. What if we need to customize this file for each environment? Or having a new environment such as a staging environment with its env file. How we can do that?</p><p>The simplest and safest way is to look up Laravel documentation! And indeed Laravel has addresses this issue for us in the <a href="https://laravel.com/docs/master/configuration">configuration docs</a>. The documentation says:</p><blockquote>You may also create a .env.testing file. This file will override the .env file when running PHPUnit tests or executing Artisan commands with the --env=testing option.</blockquote><p>The documentation covers the testing environment. But Laravel also can load a .env.production environment for the production environment.</p><h3>What About Lumen?</h3><p>Unfortunately, Lumen does not support this feature. It will only load the .env file from our project regardless of the environment used. This blog post shows how to implement that behavior in a Lumen project.</p><p>Laravel utilizes the <a href="https://github.com/vlucas/phpdotenv">Dotenv</a> package to load the environment variables when the application bootstrap. We can start by instantiating an instance of Dotenv (Using version 3 of Dotenv):</p><pre>\Dotenv\Dotenv::create(base_path(), &#39;.env&#39;)-&gt;overload();</pre><p>We instantiated Dotenv using .env file to load the environment variables. This will load and override the already loaded .env file again. The previous line give us a starting point to do the following:</p><pre>$env = app()-&gt;environment();<br>\Dotenv\Dotenv::create(base_path(), &#39;.env.&#39; . $env)-&gt;overload();</pre><p>The first line gets the currently loaded environment then fed it to Dotenv to load the correct .env file. So it will load .env.testing when environment is testing and .env.production when it is production.</p><p>OK, we have seen how to load different .env files, but how we can use this code? We can use it in the application service provider:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6052489951518102ff9dfe470f5f820/href">https://medium.com/media/b6052489951518102ff9dfe470f5f820/href</a></iframe><p>If only the testing environment needs customization, then we can use that code in the TestCase.php setUp method to load a testing env file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3386672e4bf7358c3b1764d806063c4/href">https://medium.com/media/b3386672e4bf7358c3b1764d806063c4/href</a></iframe><p>For a staging environment with a staging .env file or any other environment that is specific to an application other than <em>local</em>, <em>production</em> and <em>testing</em> defined by Laravel<em>, </em>I would suggest to not define these new environments and depend on them in the code base. The reason for this is to stick to Laravel and community conventions and to avoid any specific treatments for the default environments that will not map to the new environments automatically.</p><p>A better solution is to map these environments to the defined ones. So, for example, a staging environment can be mapped to the local. A pre-production environment can be mapped to the production. We can do the mapping in the deployment scripts to copy the contents of these files to the .env or any custom env file for the defined environments.</p><h3>Dotenv load vs. overload</h3><p>Our examples on using Dotenv used the over<em>load</em> method on Dotenv instance. The overload method will override the environment variables that Laravel loaded from .env file when the application bootstrapped.</p><p>On the other hand, the <em>load</em> method is additive. In that it will only add any new environment variables from new env file to the environment. Any previously loaded variables will not be overridden with new values from new env file.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=207380a06f16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostCSS in Laravel-mix]]></title>
            <link>https://medium.com/@yazeedobaid/postcss-in-laravel-mix-bc433bfcf7a?source=rss-a8cee96ce60a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc433bfcf7a</guid>
            <category><![CDATA[postcss]]></category>
            <category><![CDATA[laravel-mix]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Yazeed Obaid]]></dc:creator>
            <pubDate>Sat, 25 May 2019 11:44:45 GMT</pubDate>
            <atom:updated>2019-05-25T11:44:45.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*P8qnVGKIRx30eZuFM8sYNg.jpeg" /><figcaption>postcss and laravel-mix</figcaption></figure><p>Built on top of Webpack, Laravel mix provide a fluent and easy to use api to manage application assets and to define the build process for the application. In the other way around, PostCSS is a great tool to operate on an application CSS styles using Javascript. Simply, PostCSS apply Javascript routines to application CSS. Those routines are called PostCSS plugins.</p><p>In this blog post I’ll explain how to use postCSS in Laravel-mix? How to use <em>postcss-loader</em> Webpack loader in Laravel-mix? And how to use the loader in laravel-mix with its config file to provide a clean way to define PostCSS plugins using the config file?</p><h4>The first Attempt</h4><p>Mix has support for common CSS pre-processors including postCSS. To bring postCSS to Laravel-mix we can use the <em>postCss</em> api on mix like so:</p><pre>// webpack.mix.js</pre><pre>const mix = require(&#39;laravel-mix&#39;);</pre><pre>mix.js(&#39;resources/js/app.js&#39;, &#39;public/js&#39;)<br>   .postCss(&#39;resources/css/app.css&#39;, &#39;public/css&#39;);</pre><p>Easy right? Taking this a step further, <em>postCss</em> method also take a third argument as an array of postCSS plugins.</p><pre>// webpack.mix.js</pre><pre>const mix = require(&#39;laravel-mix&#39;);</pre><pre>// A purgecss extractor class to define which unused CSS classes to // remove<br>TailwindExtractor = class TailwindExtractor {<br>    static extract(content) {<br>        return content.match(/[A-Za-z0-9-_:/]+/g) || []<br>    }<br>};</pre><pre>mix.js(&#39;resources/js/app.js&#39;, &#39;public/js&#39;)<br>    .postCss(&#39;resources/css/app.css&#39;, &#39;public/css&#39;, [<br>        require(&#39;tailwindcss&#39;),<br>        require(&#39;@fullhuman/postcss-purgecss&#39;)({<br>            content: [<br>                &#39;./resources/js/*/*.vue&#39;,<br>            ],<br>            whitelist: [&#39;html&#39;, &#39;body&#39;],<br>            extractors: [<br>                {<br>                    extractor: TailwindExtractor,<br>                    extensions: [&#39;vue&#39;]<br>                }<br>            ]<br>        }),<br>        require(&#39;cssnano&#39;)<br>    ])</pre><p>I have added <em>tailwindCSS </em>(Tailwind is a utility-first CSS framework), <em>purgecss </em>and <em>cssnano </em>plugins. Mix will pipe and execute the plugins in the same order as we specify them. the above plugins will do the following; PostCSS will call tailwindCSS to generate its CSS, purgecss will remove unused TailwindCSS classes using the extractor defined above. Finally cssnano will minify our CSS file .</p><p>Under the hood, mix at the end of the build will add the autoprefixer plugin to add cross-browser support for your CSS. Cool right?</p><h4>What about using postcss-loader in Mix?</h4><p><em>postcss-loader </em>Webpack loader<em> </em>provide a clean way to use postCSS in an application be defining a config file for the postCSS plugins.</p><p>We can install the loader using npm;</p><pre>$ npm i -D postcss-loader</pre><p>To use the loader in our build, mix has rescued us again with another api. Mix provide an api to modify its default Webpack config file using <em>webpackConfig</em> method.</p><pre>// webpack.mix.js</pre><pre>const mix = require(&#39;laravel-mix&#39;);</pre><pre>mix.js(&#39;resources/js/app.js&#39;, &#39;public/js&#39;)<br>    .postCss(&#39;resources/css/app.css&#39;, &#39;public/css&#39;)<em><br>    </em>.webpackConfig({<br>        module: {<br>            rules: [<br>                {<br>                    test: /\.css/,<br>                    use: [{loader: &quot;postcss-loader&quot;, options: {}}]<br>                }<br>            ]<br>        }<br>    })</pre><p>Now <em>postcss-loader</em> with its config file is in your hands. You can now define your postCSS plugins in <em>postcss.config.js</em> file. Back to our example above, here the resulted <em>postcss.config.js</em> file which contains our postCSS plugins from mix config file:</p><pre>// postcss.config.js</pre><pre>const TailwindExtractor = class TailwindExtractor {<br>    static extract(content) {<br>        return content.match(/[A-Za-z0-9-_:/]+/g) || []<br>    }<br>};<br><em><br></em>module.exports = {<br>    plugins: {<br>        &#39;tailwindcss&#39;: {},<br>        &#39;@fullhuman/postcss-purgecss&#39;: {<br>            content: [<br>                &#39;./resources/js/*/*.vue&#39;,<br>            ],<br>            whitelist: [&#39;html&#39;, &#39;body&#39;],<br>            extractors: [<br>                {<br>                    extractor: TailwindExtractor,<br>                    extensions: [&#39;vue&#39;]<br>                }<br>            ]<br>        },<br>        &#39;cssnano&#39;: {}<br>    }<br>};</pre><p>Everything works as we want! right? But we don’t want things to just work? Let us revise what we have done. We have modified mix default Webpack config file by adding <em>postcss-loader</em> to the build and eventually to Webpack config file. But, it feels that this is not the right place to put this type of configurations in, so let us clean things up!</p><h4>Its time for some Clean ups!</h4><p>Let us imagine that we want to use the <em>postcss-loader</em> with a method call, let us write that down;</p><pre>// webpack.mix.js</pre><pre>require(&#39;postCssConfig&#39;);</pre><pre>mix.js(&#39;resources/js/app.js&#39;, &#39;public/js&#39;)<br>    .postCss(&#39;resources/css/app.css&#39;, &#39;public/css&#39;)<br>    .<strong>postCssConfig</strong>();</pre><p>Much much cleaner…</p><p>How can we define this method on mix object? Simply by <a href="https://laravel-mix.com/docs/4.0/extending-mix">extending mix</a>! Mix provide a way to extend its functionality. As described in the documentation, we can define a class with predefined methods that we can work on. Our api class can be described as follows;</p><pre>// postCssConfig.js</pre><pre>const mix = require(“laravel-mix”);</pre><pre>class LaravelMixPostCssConfigPlugin {<br>    <br>    name() {<br>        return &quot;postCssConfig&quot;;<br>    }<br><br>    dependencies() {<br>        return [&quot;postcss-loader&quot;];<br>    }<br><br>    register(options = {}) {<br>        this.options = options;<br>    }<br><br>    webpackRules() {<br>        return {<br>            rules: [<br>                {<br>                  test: /\.css/,<br>                  use: [{ loader: &quot;postcss-loader&quot;, options: this.options }]<br>                }<br>            ]<br>        };<br>    }<br>}<br><br>mix.extend(&quot;postCssConfig&quot;, new LaravelMixPostCssConfigPlugin());</pre><p>I have used three methods from the class that mix define for its extension that are relevant to our api. The <em>name </em>method is used to define the method name that we want to call our api with. <em>dependencies</em> define any npm packages that we depend on. And <em>webpackRules</em> method define our api. The later will merge the rule(s) we provide with mix’s default rules. the last statement register our api to mix. And that’s it! Our <em>webpack.mix.js</em> file is much better and cleaner.</p><h4>Conclusion</h4><p>keeping mix config file simpler and cohesion for defining build processes, and extracting configurations and plugins to their own files, will make our build process maintainable and easy to interact with.</p><p>I have created an npm package that define this laravel-mix plugin we have built in this blog post. You can check it out on GitHub;</p><p><a href="https://github.com/yazeedobaid/laravel-mix-postcss-config">yazeedobaid/laravel-mix-postcss-config</a></p><p>Resources:</p><ol><li><a href="https://laravel-mix.com/docs/4.0/installation">Laravel-mix documentation</a></li><li><a href="https://github.com/postcss/postcss-loader">postcss-loader</a></li><li><a href="https://webpack.js.org/configuration/module/">Webpack loaders and rules</a></li><li><a href="https://tailwindcss.com/">TailwindCSS</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc433bfcf7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>