<?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 Daniel Cook on Medium]]></title>
        <description><![CDATA[Stories by Daniel Cook on Medium]]></description>
        <link>https://medium.com/@petrefax66?source=rss-4565ddb93b3f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SAqwhqK9F2FdR8gOg17xyg.jpeg</url>
            <title>Stories by Daniel Cook on Medium</title>
            <link>https://medium.com/@petrefax66?source=rss-4565ddb93b3f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 01:46:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@petrefax66/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[Beginning .NET Core development with docker on Linux]]></title>
            <link>https://itnext.io/beginning-net-core-development-with-docker-on-linux-6595a7eebdaa?source=rss-4565ddb93b3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6595a7eebdaa</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Daniel Cook]]></dc:creator>
            <pubDate>Tue, 03 Jul 2018 06:58:32 GMT</pubDate>
            <atom:updated>2018-07-03T07:29:10.122Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beginning .NET Core development with docker on Linux, Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7d8QOJeM1Us3OfcF" /><figcaption>Photo by <a href="https://unsplash.com/@trevinrudy?utm_source=medium&amp;utm_medium=referral">Trevin Rudy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>.NET core came with many revolutions in the way that .NET apps were written not least the ability to do cross-platform development. My main platform of choice for development currently is Linux and I wanted to setup a development workflow that included .NET core as a back-end to a Single Page JavaScript application. Whilst I was at it I figured it should use docker containers to simplify build and deployment.</p><p>The end result is <a href="https://github.com/dfcook/core-docker">here</a>, however I want to walk through each stage and try to explain what the purpose of each configuration file is and what particular settings are used for. Whilst I am running on Linux I hope that following along on a Windows machine should not be too tricky. I have verified that the code runs on a Mac without any changes.</p><p>This is part 1 of the article focusing on the .NET container build and introducing some docker commands. Part 2 will add the UI layer and look at composing containers together.</p><h4>Prerequisites</h4><ol><li><a href="https://www.microsoft.com/net/learn/get-started/linux/ubuntu18-04">.NET Core SDK</a></li><li><a href="https://docs.docker.com/install/linux/docker-ce/ubuntu/">Docker</a></li><li><a href="https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions">Node</a></li><li><a href="https://code.visualstudio.com/">Visual Studio Code </a>— Or any editor, I like VS Code and it has extensions for docker that allow us a graphical view of the deployed images and containers.</li></ol><h4>What we are building</h4><p>There is not much in the way of C# or JavaScript coding in this story, I am going to use the dotnet and Vue cli’s to generate basic applications and have the JavaScript app call the dotnet app and display some basic data. The point of this story is to show how the applications are encapsulated in containers and composed together.</p><h4>Why use docker?</h4><p>Docker containers make it incredibly easy to reproduce your application on different machines. For instance, once I’d completed development on Linux I went to my mac, cloned the repo and ran “docker-compose up”. After downloading and building, the application was available in my browser with no further installation.</p><p>Containers also provide isolation - dependencies and settings used in the containers do not impact any other software running on your machine. This helps with avoiding dependency conflicts.</p><p>Deployment can be greatly simplified with docker, images can be pulled from a central hub once built, applications do not need to be rebuilt when moving from development to staging to production.</p><h4>Let’s go — building our API</h4><p>First things first, create a folder called core-docker and then open it in your terminal. Enter the following:</p><pre>mkdir core-api<br>cd core-api</pre><pre>dotnet new webapi<br>dotnet restore</pre><p>This will create a new webapi project and restore all its dependencies. The latest version of .NET enables HTTPS redirection by default and we don’t need it here so I made a small change in Startup.cs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*rF1Pxk9ah8oYRHgZa2Dhmg.png" /><figcaption>Startup.cs</figcaption></figure><p>Once this is done, enter “dotnet run” in your terminal and the api will begin running on port 5000, if you navigate to <a href="http://localhost:5000/api/Values">http://localhost:5000/api/Values</a> in your browser you should see a JSON response of [“value1”,”value2&quot;].</p><h4>Building an Image</h4><p>We have a running API so let’s put it in a container. Add a file called Dockerfile and open in Visual Studio Code, this should prompt you to install the relevant extension which I recommend doing.</p><p>The Dockerfile for our API consists of 2 sections, one for building and the other for running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*GKWAMVNvKhuvCr6JzAvVFA.png" /><figcaption>Dockerfile</figcaption></figure><p>If you’ve not used docker before this can appear quite daunting however it is relatively straightforward. Each line begins with a command (FROM, COPY, RUN etc) and each command will be executed in order from top to bottom.</p><ol><li>FROM specifies a docker image to use, in line 1 we specify the dotnet 2.1 SDK image which we will use to build our application.</li><li>WORKDIR specifies a working directory inside the image. We will be using /app as our working directory.</li><li>COPY copies files from our local file system into the image. We will copy the csproj file over initially and run restore then copy all the remaining files and run dotnet publish to build our application.</li><li>The runtime portion of the file uses a different docker base image, the aspnetcore-runtime image, it copies over all the files from the build and then defines the application entrypoint.</li></ol><p>To use this file to build execute the command:</p><pre>docker build -t core-api .</pre><p>This may be quite a lengthy process but each intermediate step shows its status, you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*EOG-NIbLQ988-EekA4T7mQ.png" /></figure><p>If you now run:</p><pre>docker image ls</pre><p>This will list all the images on your system and you should see the newly built core-api:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*PNJBGfijkTGznRhvxq63Gw.png" /></figure><p>Some interesting things to note from this step, if you look at the output from docker build you can see lots of ID’s appearing after each step. This is because docker is applying each command to your image incrementally and creating a new layer. These layers are visible using the docker history command:</p><pre>docker image history core-api:latest</pre><p>Also, different stages of the process can interact with each other. If you look at the first FROM statement we’ve tagged this as “build”, later in the “runtime” section we are referencing “build” in the COPY statement.</p><p>If you want to remove the image, you can use docker rm, this can take the image name or ID:</p><pre>docker image rm 7c67428fb17a</pre><p>If you get to the point that you’re seeing hundreds of images in docker you can ask it to automatically remove them:</p><pre>docker image prune</pre><p>Or even ask docker to do a full clean of images, containers and networks:</p><pre>docker system prune</pre><h4>Deploying a Container</h4><p>Now we have an image, our built application, we need to get it up and running. We do this with the docker “run” command:</p><pre>docker run core-api:latest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oi3KTpGzekxGuv_d3CH-DA.png" /></figure><p>This is the simplest way to start a container, if you then run:</p><pre>docker container ls</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z9CGLAO7anI_dZvwXzFOWA.png" /></figure><p>You can see the container is up and running, but in Production mode, not Development as it was when we started it using the dotnet command. Also, if you visit <a href="http://localhost/api/Values">http://localhost/api/Values</a> you should get an error not the JSON response we are expecting. And look at the name docker has given our container, it’s a randomly generated name of docker’s devising, not great if we want to be able to consistently refer to our container in the future.</p><p>We can fix all these things with command-line arguments. First of all stop our container from running and remove it:</p><pre>docker container stop stoic_goldstine<br>docker container rm stoic_goldstine</pre><p>(You will need to replace stoic_goldstine with the name of your container returned from docker container ls)</p><p>Now, start your container again using this command:</p><pre>docker run --name core-api --env ASPNETCORE_ENVIRONMENT=Development -p 80:80 core-api:latest</pre><p>We have added 3 arguments, — name is the name of the container when it’s up and running, — env allows us to pass environment variables to the running container and, perhaps most importantly, -p allows us to map ports on the container to ports on our machine.</p><p>When this container starts you can use the ls command and see the name and port mapping we provided:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w3ifbVCbaHH_WifW7bIhPg.png" /></figure><p>And if you go to <a href="http://localhost/api/Values">http://localhost/api/Values</a> you should get the JSON response expected.</p><h4>Job’s done</h4><p>That is it for this part. Part 2 will go into creating a simple web UI that talks to the API, adding it to its own container and then composing our containers together to complete our development environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6595a7eebdaa" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/beginning-net-core-development-with-docker-on-linux-6595a7eebdaa">Beginning .NET Core development with docker on Linux</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Do You Do Your Todos?]]></title>
            <link>https://itnext.io/how-do-you-do-your-todos-cc6ece298bb2?source=rss-4565ddb93b3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc6ece298bb2</guid>
            <category><![CDATA[redux-saga]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[mobx]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Daniel Cook]]></dc:creator>
            <pubDate>Mon, 07 May 2018 12:08:39 GMT</pubDate>
            <atom:updated>2018-05-07T21:08:15.454Z</atom:updated>
            <content:encoded><![CDATA[<h4>State management options in React 16.3 with Typescript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YKcGcfLc7R5eRXhw." /><figcaption>“Modern geometric neon bridge architecture at night on walkway, High Trestle Trail Bridge” by <a href="https://unsplash.com/@tonywebster?utm_source=medium&amp;utm_medium=referral">Tony Webster</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As Javascript applications moved beyond small nuggets of script or plain DOM manipulation into fully-fledged Single Page Applications several problems of scale emerged. One, the problem of code organization, went through various iterations (gulp, grunt, bower etc) until <a href="https://webpack.js.org/">Webpack</a> and <a href="https://www.npmjs.com/">NPM</a> came to rule the roost as bundler and dependency manager of choice. Eventually some of the brightest minds in the community turned their attention to the scalability of data and state management became a hot topic. The <a href="http://www.flux.io/%E2%80%8E">Flux</a> architecture, with its core of immutability and unidirectional data flow, which originated in Facebook proved the stimulus for various state management solutions.</p><p>Some frameworks (e.g. Vue with Vuex) have an official state management package. React has redux which is undeniably the most popular solution, however there are alternatives and, even in redux, there are problems to be solved around how to model side-effects (think remote data access as a common side effect).</p><p>With the arrival of React 16.3 the React Context API went from an undocumented and unstable part of the architecture to another potential alternative for smaller applications. I decided to produce a canonical Todo application using 6 different approaches to get a flavour of how they differ from each other. The 6 state management options are:</p><ol><li><a href="https://github.com/dfcook/react-todos">Local state </a>— setState and passing state around using props</li><li><a href="https://github.com/dfcook/react-todos/tree/master/src#redux-thunk">Redux w/ redux-thunk</a></li><li><a href="https://github.com/dfcook/react-todos/tree/redux-observable">Redux w/ redux-observable</a></li><li><a href="https://github.com/dfcook/react-todos/tree/redux-saga">Redux w/ redux-saga</a></li><li><a href="https://github.com/dfcook/react-todos/tree/mobx">Mobx</a></li><li><a href="https://github.com/dfcook/react-todos/tree/react-context">React Context</a> — setState and using the context to pass data to child components</li></ol><p>The code is <a href="https://github.com/dfcook/react-todos">here</a>. The master branch implements the baseline solution using local state and each other state management option is a branch from that, as explained in the readme. Each solution also uses typescript and the <a href="https://ant.design/docs/react/introduce">antd</a> component library.</p><p>There are already a whole host of examples available online, the reason I thought it was worth another is that I found some of them used older versions of the state management libraries or of typescript and wouldn’t work as written. I hope to keep the code up to date as new versions are released. Hopefully this will be useful for people taking a look at these options.</p><h4><a href="https://github.com/dfcook/react-todos">Local State</a></h4><p>React components, non-functional ones at least, come with their own state management API, setState. State is local to the component and initialized with a class level property:</p><pre>interface AppState {<br>  filter: string;<br>  todosLoading: boolean;<br>  todos: Todo[];<br>}</pre><pre>....</pre><pre>state: AppState = {<br>  filter: &#39;ALL&#39;,<br>  todosLoading: false,<br>  todos: []<br>};</pre><p>Updates to the state object however are not made by directly mutating this class level property, instead you should call setState passing in either a set of state changes which will be merged with the current state or a function which takes the current state and props of the component as parameters and again returns an object of changes to be merged into the component state.</p><pre>addTodo = async (title: string) =&gt; {<br>  const response = await api.add(title);</pre><pre>  this.setState({<br>    todos: [ ...this.state.todos, response.data ]<br>  });<br>}</pre><p>As state is local to a single component, it is shared with sub-components via props. Props can be data from the state or functions that will be called to propagate state updates via setState.</p><p>This is already a sophisticated state management option, based on sound principles of immutability and unidirectional data flow. Indeed, as the creator of Redux himself has stated, <a href="https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367">you may not need it</a>. However, as your application grows you may find the props passing becomes tedious and error-prone, as different parts of your app attempt to share the same data the state is pushed higher and higher up the hierarchy. At that point you may decide you need Redux.</p><h4><a href="https://github.com/dfcook/react-todos/tree/master/src#redux-thunk">Redux w/ redux-thunk</a></h4><p><a href="https://github.com/reactjs/redux">Redux</a> is a “predictable state container for JavaScript app”. It is a way of taking the local state and putting it into a container (known as a store), this can then be connected to components in your application who can receive data from the store as props and dispatch updates to the store as actions. The terminology around redux (reducers, action creators) can seem arcane for developers coming from an object-oriented background however once it clicks they become relatively straightforward, in fact the core functionality of redux itself can be implemented in ~20 lines of code!</p><p>A reducer is a function which takes the current state and an action object and returns the new state.</p><pre>export default (state: AppState, action: TodoAction): AppState =&gt; {<br>  switch (action.type) {<br>    case ActionTypes.ADD_TODO_SUCCESS:<br>      return {<br>        ...state,<br>        todos: [ ...state.todos, (action as AddTodoAction).todo]<br>      };<br>  }<br>}</pre><p>An action is a plain javascript object with a type property (string) and a payload.</p><pre>{<br>  type: &#39;ADD_TODO_SUCCESS&#39;,<br>  todo: {<br>    text: &#39;Walk the dog&#39;,<br>    completed: false<br>  }<br>}</pre><p>Redux is often associated with React as it works so well with it, however it can be used in other JavaScript frameworks. To link our React components to the store we build “Containers”, these use the react-redux “connect” higher-order function to link component props to state properties and actions. Our components can then be easy to test functional components with no knowledge of the state management system being used.</p><p><a href="https://github.com/gaearon/redux-thunk">Redux</a> is extensible through the use of middleware, one such is redux-thunk which solves the problem of asynchronous actions by allowing action creators to return a function rather than the action object. This allows side-effects such as calls to an external API to be rolled into our store actions.</p><pre>export const addTodo = (title: string) =&gt; {<br>  return async (dispatch: Dispatch) =&gt; {<br>    const response = await api.add(title);<br>    dispatch(addTodoSuccess(response.data));<br>  };<br>};</pre><h4><a href="https://github.com/dfcook/react-todos/tree/redux-observable">Redux w/ redux-observable</a></h4><p>Redux-observable is another middleware for redux asynchronous actions, it approaches the problem from an alternative direction, using <a href="http://reactivex.io/rxjs/">RxJS</a> observables. The core concept is the “Epic”, a function which receives a stream of actions and returns a stream of actions.</p><pre>const fetchTodoEpic = (action$: ActionsObservable&lt;FetchTodosAction&gt;) =&gt;<br>  action$<br>    .ofType(ActionTypes.FETCH_TODOS)<br>    .mergeMap((action: FetchTodosAction) =&gt;<br>      Observable.ajax({<br>        url: baseUrl,<br>        withCredentials: false,<br>        crossDomain: true<br>      })<br>      .map(req =&gt; fetchTodosSuccess(req.response)));</pre><p>RxJS comes with a large amount of “operators”, functions for manipulating the stream such as mergeMap in the example above. For instance, the takeUntil operator allows an action to be dispatched which cancels the async operation, a big selling point of redux-observable.</p><h4><a href="https://github.com/dfcook/react-todos/tree/redux-saga">Redux w/ redux-saga</a></h4><p>Redux-saga is yet another middleware for redux that is aimed at making side-effects easier. It uses ES6 generators which means that the async flows become incredibly easy to read (assuming you understand the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function%2A">generator</a> syntax).</p><pre>export function* fetchTodos() {<br>  yield put(updateLoading(true));<br>  const response = yield call(api.fetch);<br>  yield put(loadTodosSuccess(response.data));<br>  yield put(updateLoading(false));<br>}</pre><p>Out of the 3 redux middlewares this was the one I enjoyed using the most, I think the separation between sagas and actions makes the end-user code very readable and simple to understand and test.</p><h4><a href="https://github.com/dfcook/react-todos/tree/mobx">Mobx</a></h4><p><a href="https://mobx.js.org/">Mobx</a> takes a very different approach to state management to Redux, one that will be very familiar to developers who have come from Vue and Vuex. A Mobx store is “reactive”, you choose the shape of the data structure that aligns with your state and then use annotations to mark it as observable. Your components then use an observer annotation to enable them to react to changes in the store state.</p><pre>@observable todosLoading = false;<br>@observable todos: Todo[] = [];</pre><pre>async refreshTodos() {<br>  this.todosLoading = true;<br>  <br>  const response = await api.fetch();<br>  this.todos = response.data;</pre><pre>  this.todosLoading = false;<br>}</pre><p>Coming from Redux and setState this is a bit of a culture shock, where is the immutability? It is certainly very different however it allows some nice abstractions, for instance the computed annotation allows computed property logic to be placed in the store.</p><pre>@computed get filteredTodos() {<br>  switch (this.filter) {<br>    case &#39;ACTIVE&#39;:<br>      return this.todos.filter(todo =&gt; !todo.completed);</pre><pre>    case &#39;COMPLETED&#39;:<br>      return this.todos.filter(todo =&gt; todo.completed);</pre><pre>    default:<br>      return this.todos;<br>  }<br>}</pre><h4><a href="https://github.com/dfcook/react-todos/tree/react-context">React Context</a></h4><p>React’s context API has long been marked as experimental and subject to change, however its consumer/provider model was the basis for Redux’s providers. With 16.3 the API has stabilised and is now another option for state management.</p><p>Similarly to the local state option state and the functions that operate on it sit in a components towards the top of the hierarchy. However instead of passing the state into sub-components via props it is placed in a context using the createContext function.</p><pre>export interface AppState {<br>  filter: string;<br>  loading: boolean;<br>  todos: Todo[];<br>  updateFilter: (filter: string) =&gt; void;<br>  addTodo: (title: string) =&gt; void;<br>  toggleTodo: (todo: Todo) =&gt; void;<br>  deleteTodo: (todo: Todo) =&gt; void;<br>}</pre><pre>export const TodoContext = React.createContext&lt;AppState&gt;({<br>  filter: &#39;ALL&#39;,<br>  loading: false,<br>  todos: [],<br>  updateFilter: (filter: string) =&gt; {},<br>  addTodo: (title: string) =&gt; {},<br>  toggleTodo: (todo: Todo) =&gt; {},<br>  deleteTodo: (todo: Todo) =&gt; {}<br>});</pre><p>TodoContext in the code above is an object with 2 properties, Provider and Consumer, these can then be used in our component JSX to hook components up to the context. The Consumer is notable as it uses another pattern, the “render prop” to allow the context to be accessed when rendering a child component.</p><p>I hope that the brief descriptions above and, more importantly, the code give a straightforward introduction to each method of state management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc6ece298bb2" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-do-you-do-your-todos-cc6ece298bb2">How Do You Do Your Todos?</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js and Webpack 4 From Scratch, Part 3]]></title>
            <link>https://itnext.io/vue-js-and-webpack-4-from-scratch-part-3-3f68d2a3c127?source=rss-4565ddb93b3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f68d2a3c127</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Daniel Cook]]></dc:creator>
            <pubDate>Mon, 26 Mar 2018 08:42:05 GMT</pubDate>
            <atom:updated>2018-11-24T18:18:13.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-4FrGyvSUi7TwDV_." /></figure><h3>Packing up</h3><p>This is the final part in this series on configuring a Vue project from scratch using Webpack 4, part 1 is available <a href="https://itnext.io/vuejs-and-webpack-4-from-scratch-part-1-94c9c28a534a">here</a> and part 2 <a href="https://itnext.io/vue-js-and-webpack-4-from-scratch-part-2-5038cc9deffb">here</a>. Below I’ll cover:</p><ol><li>Linting.</li><li>Testing.</li><li>Processing of static assets.</li></ol><p>And, based on a question from a previous article, I’ll also mention css extraction.</p><p>The final code is available on <a href="https://github.com/dfcook/vue-webpack4-template">github</a>.</p><p>In a comment on part 1, <a href="http://twitter.com/blacksonic86">@blacksonic86</a> suggested that the entry point for our application should be called index.js, rather than app.js. This makes a lot of sense as it is the default in webpack 4 meaning we can remove it from our webpack.config.dev.js.</p><p>In practice I often have multiple entrypoints as I use this configuration to add polyfills to support older browsers such as Internet Explorer but in this case it’s a change I should have thought of. Changing the name of the file means that the current webpack configuration is as below.</p><pre>&#39;use strict&#39;</pre><pre>const webpack = require(&#39;webpack&#39;)<br><em>const</em> { VueLoaderPlugin } = require(&#39;vue-loader&#39;)<br>const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;)</pre><pre>module.exports = {<br>  mode: &#39;development&#39;,<br>  <br>  devServer: {<br>    hot: true,<br>    watchOptions: {<br>      poll: true<br>    }<br>  },  module: {<br>    rules: [<br>      {<br>        test: /\.vue$/,<br>        use: &#39;vue-loader&#39;<br>      }, {<br>        test: /\.js$/,<br>        use: &#39;babel-loader&#39;<br>      }, {<br>        test: /\.styl(us)?$/,<br>        use: [ &#39;vue-style-loader&#39;, &#39;css-loader&#39;, &#39;stylus-loader&#39; ]<br>      }<br>    ]<br>  },</pre><pre>plugins: [<br>    new webpack.HotModuleReplacementPlugin(),<br>    new VueLoaderPlugin(),<br>    new HtmlWebpackPlugin({<br>      filename: &#39;index.html&#39;,<br>      template: &#39;index.html&#39;,<br>      inject: true<br>    }) <br>  ]<br>}</pre><h3>Linting</h3><p>Linting is the process of applying static analysis to your codebase to detect issues or enforce style guidelines. It is very useful when working with dynamically typed languages such as javascript. <a href="https://eslint.org/">ESLint</a> is the standard linter, it allows you to define sets of rules to run against your codebase, or use plugins to use a pre-defined set. We will use the Vue eslint plugin to enforce the recommended rules for a Vue application.</p><p>There are quite a few npm packages we need to install to enable linting:</p><pre>npm install --save-dev eslint eslint-plugin-import eslint-plugin-node eslint-plugin-promise eslint-plugin-standard eslint-config-standard babel-eslint eslint-loader eslint-plugin-vue</pre><p>Once this is done, we need to tell eslint which rules we want to use, create a file called .eslintrc.js in the project root and and add these settings:</p><pre>module.exports = {<br>  parserOptions: {<br>    parser: &#39;babel-eslint&#39;<br>  },<br>  extends: [<br>    &#39;plugin:vue/recommended&#39;,<br>    &#39;standard&#39;<br>  ],<br>  plugins: [<br>    &#39;vue&#39;<br>  ]<br>}</pre><p>Here we are telling eslint that we want to use babel to parse our javascript and then apply the standard linting rules and the recommended rules from the vue plugin.</p><p>The easiest way to run ESLint is via an npm script. Add this to package.json in the scripts section:</p><pre>&quot;lint&quot;: &quot;eslint --ext .js,.vue src&quot;</pre><p>We’re running ESLint against anything in our src folder with the file extension .js or .vue. Running this now and you should actually get an error already.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_GRZIzRzeuiqviHZ3DfdQ.png" /></figure><p>This is pointing at these lines in our index.js, I have the eslint extension for VSCode installed so if I open this file now I can see another visual cue that something is wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*8yC-DK5fI0aeCJAUTOFCpQ.png" /></figure><p>There are various ways to fix this, we could export the new Vue object for instance, however let’s tell ESLint that this line is actually OK and we want it to ignore it. Add this comment immediately before the offending code:</p><pre>/* eslint-disable-next-line no-new */</pre><p>Now when you rerun our lint script it should report no errors.</p><p>ESLint also supports autofixing some classes of errors, I like to add a shortcut script to my npm config to allow me to run the autofix when required:</p><pre>&quot;lint:fix&quot;: &quot;eslint --ext .js,.vue src --fix&quot;</pre><p>Once our linting is configured to run on-demand we want to change our webpack build so it runs automatically. For this we need to install the webpack loader:</p><pre>npm install --save-dev eslint-loader</pre><p>And change our webpack config to add a rule to associate our .js and .vue files with the ESLint loader:</p><pre>{<br>  test: /\.(js|vue)$/,<br>  use: &#39;eslint-loader&#39;,<br>  enforce: &#39;pre&#39;<br>}</pre><p>This rule has one change to our others, enforce: ‘pre’. This means the ESLint loader is a pre-loader, it will run before the other loaders and apply the linting rules before the babel-loader kicks in and start processing the javascript.</p><h3>Static Assets</h3><p>Static assets are things like images and video, they will not be processed by Webpack but we will require them to be copied to our dist folder so they will be available to the built application.</p><p>To do this we use the copy-webpack-plugin. Following the by-now familiar path we need to install the package:</p><pre>npm install --save-dev copy-webpack-plugin</pre><p>Then in our webpack config we pull the plugin in and add it to our plugins section.</p><pre>const CopyWebpackPlugin = require(&#39;copy-webpack-plugin&#39;)<br><em>const</em> path = require(&#39;path&#39;)</pre><pre>function resolve (dir) {<br>  return path.join(__dirname, &#39;..&#39;, dir)<br>}</pre><pre>plugins: [<br>  new CopyWebpackPlugin([{<br>    from: resolve(&#39;static/img&#39;),<br>    to: resolve(&#39;dist/static/img&#39;),<br>    toType: &#39;dir&#39;<br>  }])<br>]</pre><p>This is pretty straightforward, all the images we put in our static/img folder will be copied to the equivalent folder in our dist build folder.</p><h3>Testing</h3><p>Part of the Vue ecosystem, vue-test-utils is the official unit testing library for Vue.js. It supports multiple test runners, shallow rendering, simulating user interactions, mocking vuex and vue-router and synchronous updates (removing the need for calling nextTick to trigger dom updates).</p><p>In this example, I’m going to use <a href="https://facebook.github.io/jest/">jest</a> for running the tests. Jest is from facebook and is closely associated with React, however it is can adapt to any Javascript library or framework and there is a vue-specific ecosystem allowing us to run our tests without any difficulty.</p><p>Let’s install jest:</p><pre>npm install --save-dev jest babel-jest vue-jest jest-serializer-vue @vue/test-utils</pre><p>Jest is the test-runner, vue-jest is a package for transforming vue components into the correct format for jest and jest-serializer-vue is a package that supports taking snapshots of vue components. Snapshot testing allows rendering of a complete DOM and then performing comparisons to ensure it does not change.</p><p>Instead of a standalone configuration file, Jest is configured from our package.json. Add this to the end of our json object:</p><pre>&quot;jest&quot;: {<br>  &quot;moduleFileExtensions&quot;: [<br>    &quot;js&quot;,<br>    &quot;vue&quot;<br>  ],<br>  &quot;moduleNameMapper&quot;: {<br>    &quot;^@/(.*)$&quot;: &quot;&lt;rootDir&gt;/src/$1&quot;<br>  },<br>  &quot;transform&quot;: {<br>    &quot;^.+\\.js$&quot;: &quot;&lt;rootDir&gt;/node_modules/babel-jest&quot;,<br>    &quot;.*\\.(vue)$&quot;: &quot;&lt;rootDir&gt;/node_modules/vue-jest&quot;<br>  },<br>  &quot;snapshotSerializers&quot;: [<br>    &quot;&lt;rootDir&gt;/node_modules/jest-serializer-vue&quot;<br>  ]<br>}</pre><p>While we’re in package.json let’s add a script to actually run our tests:</p><pre>&quot;test&quot;: &quot;jest&quot;</pre><p>We need to configure babel to transpile our tests, add this to the .babelrc file:</p><pre>&quot;env&quot;: {<br>  &quot;test&quot;: {<br>    &quot;presets&quot;: [<br>      [&quot;env&quot;, { &quot;targets&quot;: { &quot;node&quot;: &quot;current&quot; }}]<br>    ]<br>  }<br>}</pre><p>And tell ESLint about our test environment by adding this to the .eslintrc.js file:</p><pre>env: {<br>  browser: true,<br>  node: true,<br>  mocha: true<br>},<br>globals: {<br>  expect: true<br>}</pre><p>Now jest is configured we can actually write a test. Keeping it simple we will just mount our App component and verify that it has the “.center-content” class. Jest will by default look for tests in a folder called __tests__ so create this under the src folder and add a file called App.spec.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*nRn28jttdn-Mhq_OgBwuTA.png" /></figure><p>We use Vue test-utils to mount the app and then run a simple expect against the returned wrapper.</p><p>To run this test it’s as simple as:</p><pre>npm run test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hA2RnAOXSV1tBYmWANIGCA.png" /></figure><h3>Extracting CSS</h3><p>This was something that <a href="https://medium.com/u/1fa725babd08">Ahsath</a> asked about in the comments to part 2. It’s a testament to the pace of change in the webpack arena that in the week since I published that the method of extracting CSS into a separate file has changed completely. With the release of vue-loader 15 MiniCssExtractPlugin is the standard way to extract CSS from your Vue single-file-components.</p><p>Install the plugin from npm:</p><pre>npm install --save-dev mini-css-extract-plugin</pre><p>Add it to the plugins in our webpack config file:</p><pre>const MiniCssExtractPlugin  = require(&#39;mini-css-extract-plugin&#39;)</pre><pre>.<br>.<br>plugins: [<br>  new MiniCssExtractPlugin({<br>    filename: &#39;main.css&#39;<br>  })<br>]</pre><p>And finally configure our stylus loader to use this plugin to extract the css and the vue loader to extract the CSS from our single file components:</p><pre>module: {<br>  rules: [<br>    {<br>      test: /\.vue$/,<br>      use: &#39;vue-loader&#39;<br>    }, {<br>      test: /\.styl(us)?$/,<br>      use: [<br>        MiniCssExtractPlugin.loader,<br>        &#39;css-loader&#39;,<br>        &#39;stylus-loader&#39;<br>      ]<br>    }<br>  ]<br>}</pre><p>Now when our application builds all the stylus will be extracted and placed in a single css file (main.css) under our dist folder. Scoped CSS from our single-file-components will also be included, for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*N2r3Ro8Z0wDO56ExKem8yQ.png" /></figure><h3>That’s All Folks</h3><p>I hope these articles have been helpful. With the imminent arrival of vue-cli 3 there is an element of obsolescence to them already, the method of working with webpack will go through significant changes. However, it will always be important to have some knowledge of how these things are configured under the hood, and there is no better way to do that than working through from scratch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f68d2a3c127" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/vue-js-and-webpack-4-from-scratch-part-3-3f68d2a3c127">Vue.js and Webpack 4 From Scratch, Part 3</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js and Webpack 4 From Scratch, Part 2]]></title>
            <link>https://itnext.io/vue-js-and-webpack-4-from-scratch-part-2-5038cc9deffb?source=rss-4565ddb93b3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5038cc9deffb</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Daniel Cook]]></dc:creator>
            <pubDate>Sun, 18 Mar 2018 09:22:12 GMT</pubDate>
            <atom:updated>2018-11-24T18:11:46.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TODhOOKZIjarrlYV." /></figure><blockquote><a href="https://www.linkedin.com/cws/share?url=https%3A%2F%2Fitnext.io%2Fvue-js-and-webpack-4-from-scratch-part-2%E2%80%935038cc9deffb">Click here to share this article on LinkedIn »</a></blockquote><h3>This time with style!</h3><p>Continuing from <a href="https://itnext.io/vuejs-and-webpack-4-from-scratch-part-1-94c9c28a534a">Part 1</a>, in this article I will continue to build our Vue.js application by adding:</p><ul><li>Stylus for adding pre-processed CSS</li><li>Hot Module Reloading and HTML injection</li><li>Babel for building our scripts</li></ul><p><a href="https://medium.com/@petrefax66/vue-js-and-webpack-4-from-scratch-part-3-3f68d2a3c127">Part 3</a> will complete the application by adding:</p><ul><li>Static assets processing</li><li>ESLint for linting</li><li>Testing using Jest</li></ul><p>Let’s start by getting webpack-dev-server setup, by doing this we won’t need to keep running our build script to see the changes in the browser.</p><p>We’ll need to install the npm module:</p><pre>npm install --save-dev webpack-dev-server</pre><p>And change our build script to run this instead of webpack, at the same time I’m going to rename the command from build to dev:</p><pre>&quot;dev&quot;: &quot;webpack-dev-server --config build/webpack.config.dev.js&quot;</pre><p>Running this now and the browser starts up on <a href="http://localhost:8080/">http://localhost:8080</a> and I can see my app. All with zero config! However, there’s a slight problem, if I change my App.vue to say “Good Evening San Dimas!” instead of “Hello World!” then the browser does not update.</p><p>If I check my console I can see the application is building so what is wrong? Well when we setup our index.html we hardcoded the path to our javascript, for hot module reloading to work we need to allow this path to be injected, that way the dev server can update the html to include the changes as and when they are made.</p><p>Go to the index.html and remove the script tag that points to dist/main.js, then install the html-webpack-plugin:</p><pre>npm install --save-dev html-webpack-plugin</pre><p>Now we need to add this to our webpack config file, so it ends up looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*JBb0P_RCJFYSpaS3QIkr0w.png" /></figure><p>If you now run the application up you can change the message in App.vue and it is immediately reloaded in the browser window!</p><p>This is awesome, however we haven’t yet got true HMR, if you look in the browser devtools you can see that the whole page is refreshed when we make a change. To fix this we need to add one more piece of configuration:</p><pre>&#39;use strict&#39;</pre><pre><em>const</em> webpack = require(&#39;webpack&#39;)<br><em>const</em> { VueLoaderPlugin } = require(&#39;vue-loader&#39;)<br><em>const</em> HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;)</pre><pre>module.exports = {<br>  mode: &#39;development&#39;,<br>  <br>  entry: [<br>    &#39;./src/app.js&#39;<br>  ],</pre><pre>  devServer: {<br>    hot: true,<br>    watchOptions: {<br>      poll: true<br>    }<br>  },</pre><pre>  module: {<br>    rules: [<br>      {<br>        test: /\.vue<em>$</em>/,<br>        use: &#39;vue-loader&#39;<br>      }<br>    ]<br>  },</pre><pre>  plugins: [<br>    new webpack.HotModuleReplacementPlugin(),<br>    new VueLoaderPlugin(),<br>    new HtmlWebpackPlugin({<br>      filename: &#39;index.html&#39;,<br>      template: &#39;index.html&#39;,<br>      inject: true<br>    })<br>  ]<br>}</pre><p>With this in place you should be able to see the changes hot loaded into the page without refreshing, something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zgaKM0YbKFP1TGDL8gWCw.png" /></figure><p>Now we have our app auto-updating we should be able to move much quicker so let’s add some CSS. Change the App.vue file so it looks like this:</p><pre>&lt;template&gt;<br>  &lt;div class=&quot;full-width center-content&quot;&gt;<br>    &lt;h1&gt;Hello World!&lt;/h1&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;style scoped&gt;<br>.full-width {<br>  width: 100%;<br>}</pre><pre>.center-content {<br>  display: flex;<br>  justify-content: center;<br>  align-items: center;<br>}<br>&lt;/style&gt;</pre><p>This change used to get applied automatically in the browser however now you will see an error message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*LpExik9-N5lMrZRiUROFtA.png" /></figure><p>There is a similar issue if the CSS is in a file of its own. Create a folder called assets in the root, add a file called app.css and copy the full-width and center-content classes into it. To include it in our app, we can import it in out app.js….</p><pre>import &#39;../assets/app.css&#39;</pre><p>…and remove the styles from App.vue.</p><p>Now, when you try to run your app there is an error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Hwm6aeB_mHgXFH9A7aEAw.png" /></figure><p>To fix this we need to configure the css loader in our webpack config, add this to rules:</p><pre>{<br>  test: /\.css$/,<br>  use: [<br>    &#39;vue-style-loader&#39;,<br>    &#39;css-loader&#39;<br>  ]<br>}</pre><p>And install the style-loaders:</p><pre>npm install --save-dev css-loader vue-style-loader</pre><p>The css should then load and we have css processing in both our external assets and our single-file components.</p><p>One final change here, I like using stylus for CSS pre-processing so I’ve installed the loader:</p><pre>npm install --save-dev stylus stylus-loader</pre><p>Added a rule:</p><pre>{<br>  test: /\.styl(us)?$/,<br>  use: [<br>    &#39;vue-style-loader&#39;,<br>    &#39;css-loader&#39;,<br>    &#39;stylus-loader&#39;<br>  ]<br>}</pre><p>And convert my app.css to app.styl:</p><pre>.full-width<br>  width 100%</pre><pre>.center-content<br>  display flex<br>  justify-content center<br>  align-items center</pre><p>At this point if you’re using VSCode there’s a stylus extension which will colour-code your styles correctly.</p><p>So far we have managed to get by without adding any script sections to our components, as this is such a simple application we’re not going to do anything too ambitious, let’s just create a HelloComponent that takes name as a prop and issues the appropriate greeting.</p><p>Under the components folder, add HelloComponent.vue, it should look like this:</p><pre>&lt;template&gt;<br>  &lt;h1&gt;Hello {{ name }}!&lt;/h1&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;</pre><pre>export default {<br>  props: {<br>    name: {<br>      type: String,<br>      required: true<br>    }<br>  }<br>}<br>&lt;/script&gt;</pre><pre>&lt;style lang=&quot;stylus&quot; scoped&gt;<br>h1<br>  color red<br>&lt;/style&gt;</pre><p>Then change App.vue to use the new component:</p><pre>&lt;template&gt;<br>  &lt;div class=&quot;full-width center-content&quot;&gt;<br>    &lt;hello-component name=&quot;World&quot; /&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>import HelloComponent from &#39;./components/HelloComponent.vue&#39;</pre><pre>export default {<br>  components: {<br>    HelloComponent<br>  }<br>}<br>&lt;/script&gt;</pre><p>This works, however older browsers may struggle with this ES6 syntax (and this is something we will come up against when we start testing) so we are going to install Babel to transpile our code to ES5 which can be understood by all browsers.</p><p>First, install the npm modules:</p><pre>npm install --save-dev @babel/core babel-loader @babel/preset-env</pre><p>Then add the loader config:</p><pre>{<br>  test: /\.js$/,<br>  use: &#39;babel-loader&#39;<br>}</pre><p>It is important at this stage that this loader config comes after vue-loader in your config, vue-loader will split out your single-file components into separate modules for your html, js and styles, we want babel-loader to process the js part of this.</p><p>Finally in the root of the project create a file called .babelrc, this is where we will put babel-specific configuration. At the moment we are going to keep this as simple as possible:</p><pre>{<br>  &quot;presets&quot;: [<br>    [&quot;@babel/env&quot;, {<br>      &quot;modules&quot;: false,<br>      &quot;targets&quot;: {<br>        &quot;browsers&quot;: [&quot;&gt; 1%&quot;, &quot;last 2 versions&quot;, &quot;not ie &lt;= 8&quot;]<br>      }<br>    }]<br>  ]<br>}</pre><p>We can now run our application up and we see no surface changes however under the hood our ES6 code has been transpiled to ES5 and will work on a much wider range of browsers.</p><p>That’s all for this part, in the final part we’ll finish up the application by looking at external asset processing, linting and testing. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5038cc9deffb" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/vue-js-and-webpack-4-from-scratch-part-2-5038cc9deffb">Vue.js and Webpack 4 From Scratch, Part 2</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js and Webpack 4 From Scratch, Part 1]]></title>
            <link>https://itnext.io/vuejs-and-webpack-4-from-scratch-part-1-94c9c28a534a?source=rss-4565ddb93b3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/94c9c28a534a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Daniel Cook]]></dc:creator>
            <pubDate>Sat, 17 Mar 2018 10:07:28 GMT</pubDate>
            <atom:updated>2018-07-23T18:57:44.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H9Adf9GRVkGBKi82." /></figure><h3>Part 1: Up and running</h3><p>My previous <a href="http://medium.com/@petrefax66/getting-started-vue-js-and-visual-studio-code-6990f92e918a">article</a> described how to create a Vue.js application using the command line interface. This is the easiest way to get started and will be suitable for the majority of needs. However, it certainly doesn’t hurt to try taking the opposite road and build an application entirely from scratch. With the release of <a href="https://medium.com/webpack/webpack-4-released-today-6cdb994702d4">Webpack 4</a> now is a good time to take this ambitious route and learn a bit more about the workings of the build and bundling process by crafting it entirely by hand.</p><p>In this article I will start with an empty folder and create a webpack build for a Vue.js application including:</p><ul><li>Hot Module loading with webpack-dev-server</li><li>Linting using eslint</li><li>CSS pre-processing with stylus</li><li>Testing using @vue/test-utils and Jest</li></ul><p>The only pre-requisite is having node and npm installed, although I will be using VSCode as my editor.</p><p>The final code for this article is available on <a href="https://github.com/dfcook/vue-webpack4-template">github</a> for reference, the official webpack templates will undoubtedly be updated to Webpack 4 shortly.</p><p>As this is quite a long process I will divide the article into parts, this first part will take us from an empty folder up to a simple page containing a Vue component bundled with webpack and opened in a browser window.</p><p><a href="https://medium.com/@petrefax66/vue-js-and-webpack-4-from-scratch-part-2-5038cc9deffb">Part 2</a> will cover hot module reloading, styling and transpilation using babel.</p><p>The <a href="https://medium.com/@petrefax66/vue-js-and-webpack-4-from-scratch-part-3-3f68d2a3c127">final part</a> covers linting, testing, static assets and CSS extraction.</p><p>The first thing to do is create a new folder, cd into it and initialise NPM:</p><p>npm init</p><p>You will be asked to provide some information about the project, it’s safe to accept defaults at this stage, and once completed you will have a package.json file entirely empty of anything other than meta-information. Now we can begin adding our packages.</p><p>npm install --save vue vue-router</p><p>This installs our application dependencies.</p><p>npm install --save-dev webpack webpack-cli</p><p>This installs webpack to allow us to begin building our application bundle.</p><h4>Application Structure</h4><p>I like to put all the application code, our javascript and vue components, in a subfolder called src. In here I will add:</p><ol><li>app.js : The application entrypoint.</li><li>App.vue: The root component</li><li>pages: A folder containing all top-level components, each of these will have a route entry associated with it.</li><li>components: A folder containing our building block components. Components will be organised into sub-folders based on feature.</li><li>router: A folder for all our vue-router configuration.</li></ol><p>If I was using vuex I would create another folder called store to contain all our actions/mutations etc.</p><p>When I create these, the folder structure should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*jRQYrW3t2qkOZYezwuPz5A.png" /></figure><p>We’ll start our app.js with possibly the simplest entrypoint possible:</p><pre>import Vue from &#39;vue&#39;<br>import App from &#39;./App.vue&#39;</pre><pre>new Vue({<br>  el: &#39;#app&#39;,<br>  render: h =&gt; h(App)<br>})</pre><p>This will pull in our App component and render it into the DOM element with id “app”. Our App component is just as simple for the moment:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;Hello World!&lt;/h1&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><p>Now we have some Vue code, we need to bundle it using Webpack so it can be pulled into our html.</p><h4>Webpack</h4><p>Webpack is a module bundler for Javascript applications, when we run the webpack command we are asking it to start at our entrypoint and then build a dependency graph of the whole application, pulling those dependencies into one or more bundles that can be included in our application. It supports multiple different file types through <strong>loaders</strong>, loaders will take files that have no concept of modules (e.g. css) and process them in a way that allows them to participate in the overall dependency graph that webpack is building.</p><p>Webpack 4 was just released with a ton of new features including:</p><ol><li>Built-in chunking support with the optimization API.</li><li>Support for 5 different module types, including Web Assembly modules.</li><li>A “mode” configuration setting that applies a sensible set of defaults, simple projects can be built relying on this alone to determine how to build your application.</li><li>Zero-config setups (#0CJS). If you supply the mode then Webpack will use default entry and output settings to build your application without the need for a config file.</li></ol><p>All this plus smaller bundle sizes and faster build times!</p><p>Let’s try out a simple webpack build.</p><p>In the root of our project create a folder called build and add a file called webpack.config.dev.js. We will use this to configure a loader for our Vue single-file components.</p><pre>&#39;use strict&#39;</pre><pre>const { VueLoaderPlugin } = require(&#39;vue-loader&#39;)</pre><pre>module.exports = {<br>  mode: &#39;development&#39;,<br>  entry: [<br>    &#39;./src/app.js&#39;<br>  ],<br>  module: {<br>    rules: [<br>      {<br>        test: /\.vue$/,<br>        use: &#39;vue-loader&#39;<br>      }<br>    ]<br>  },<br>  plugins: [<br>    new VueLoaderPlugin()<br>  ]<br>}</pre><p>The module section will contain all our loaders, each loader declaration consists of a minimum of 2 properties, test and loader. Test is a regular expression that webpack will use to identify which file types to be processed by this loader and loader is the name of the loader itself.</p><p>For this to work we need to install some more dependencies:</p><pre>npm install --save-dev vue-loader vue-template-compiler vue-style-loader css-loader</pre><p>And add an npm build script:</p><pre>&quot;build&quot;: &quot;webpack --config build/webpack.config.dev.js&quot;</pre><p>We also need to add an index.html file to pull in our built bundle, place this in the root of the project:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width,initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;My Vue app with webpack 4&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;app&quot;&gt;&lt;/div&gt;<br>    &lt;script src=&quot;dist/main.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>If you now run the build script you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pxfPPRzyQhKNopB4D_2kSA.png" /></figure><p>And if you open index.html in your browser you should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zFpgviKqRMZdzf5fhsGobg.png" /></figure><p>As an aside, there is an extension for VSCode, “Live Server”, that allows you to right-click on html files and launch them in an on-demand web server as opposed to opening them from your file system. Eventually we will serve our application using webpack-dev-server with hot module reloading but for the meantime this is an excellent stopgap.</p><h4>Next Step</h4><p>In the next part of the article I will create a component with some script to illustrate babel-compilation and configure stylus for our css. We will install webpack-dev-server and configure hot module reloading including support for static assets. To complete the application we will create a production build including splitting out of vendor modules and show how to test our application using @vue/test-utils and jest.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94c9c28a534a" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/vuejs-and-webpack-4-from-scratch-part-1-94c9c28a534a">Vue.js and Webpack 4 From Scratch, Part 1</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started: Vue.js and Visual Studio Code]]></title>
            <link>https://itnext.io/getting-started-vue-js-and-visual-studio-code-6990f92e918a?source=rss-4565ddb93b3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6990f92e918a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[visual-studio-code]]></category>
            <dc:creator><![CDATA[Daniel Cook]]></dc:creator>
            <pubDate>Sat, 10 Mar 2018 10:08:27 GMT</pubDate>
            <atom:updated>2018-03-19T00:14:22.383Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dI_ww4czTTdsu4sGr3TdXw.jpeg" /></figure><blockquote><a href="https://www.linkedin.com/cws/share?url=https%3A%2F%2Fitnext.io%2Fgetting-started-vue-js-and-visual-studio-code-6990f92e918a">Click here to share this article on LinkedIn »</a></blockquote><p>Web development in 2018 can feel like it is moving at supersonic speed. For a new developer who is coming at building their own web site for the first time it can be confusing to know exactly where to start.</p><p>This tutorial is not actually about building that site, it is intended to help you get a working environment installed on your machine so that you just need to worry about building the code you need with Vue.js and Visual Studio Code.</p><h3><a href="https://vuejs.org/">Vue.js</a></h3><p>Vue.js is a modern, progressive javascript framework for building user interfaces, in this case for building a web application. It is one of the top 3 javascript frameworks today (along with React from Facebook and Angular from Google). Unlike those other frameworks, Vue.js was originally created by a single developer, <a href="https://medium.com/u/4f198f5f1f12">Evan You</a>. It is known for its simplicity, its awesome documentation and the friendly, approachable community.</p><p>Vue comes with some great tools to make it easy to get started, particularly a <a href="https://github.com/vuejs/vue-cli/blob/dev/docs/README.md">command-line interface</a> which will take care of making sure you have the correct dependencies installed.</p><h3><a href="https://code.visualstudio.com/">Visual Studio Code</a></h3><p>Visual Studio Code (VSCode) is a free, open-source, text editor from Microsoft. It has achieved massive popularity since its release due to its plethora of extensions, regular feature additions and the speed and responsiveness of the user interface.</p><h3><a href="https://nodejs.org/">Node.js</a></h3><p>Node.js is a javascript runtime build on the V8 engine that comes with Google Chrome, it is pretty much essential for modern javascript development not least because it come with <a href="https://nodejs.org/">npm</a>, a package manager and script runner which will manage all your application’s dependencies.</p><h3>Getting started with vue-cli</h3><p>To get started, first install some software, Node.js downloads for all platforms are available <a href="https://nodejs.org/en/download/">here,</a> and VSCode is available for Mac, Windows and Linux from <a href="https://code.visualstudio.com/download">here</a>.</p><p>Once node is downloaded, we can install the Vue.js cli, open up a terminal and enter the following:</p><pre>npm install -g @vue/cli</pre><p>If you are running on linux you will need to prefix the command with sudo, and you should see output similar to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5MlS77Nd-1KIA4uwD-j5rg.png" /></figure><p>This command has installed the vue-cli on our machine as a global (hence the -g) package. This means that the “vue” command is available from the command-line. Try it now…..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IC3pquHgkpUPV_nmT_SRxQ.png" /></figure><p>Now we can use the init command to generate our web application from a template, we will use the webpack-simple template however you do not need to know all about webpack (which is a module builder and a complex topic in its own right) as vue-cli will handle that for you.</p><pre>vue init webpack-simple my-vue-app</pre><p>Entering the above command will begin the process of creating a new vue application. It will be created in the directory my-vue-app, you just need to wait for the template to download then answer some configuration questions, it is safe to leave the default answers for now.</p><p>Once installed, cd into the new directory and enter:</p><pre>npm install<br>npm run dev</pre><p>These command instruct npm to download all the dependencies your project needs and then launch your application. At this point your terminal should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjWtrn1jePLpjfN4cJnqZw.png" /></figure><p>And hopefully your browser will have opened at <a href="http://localhost:8080/">http://localhost:8080</a> with a nice welcoming page full of essential links. Congratulations! You have created your first web application with Vue.js.</p><h3>Getting started with Visual Studio Code</h3><p>Now we have our skeleton app we can open it in Visual Studio Code. Press Ctrl+C to stop the web server then enter:</p><pre>code .</pre><p>This will launch VSCode in the current directory, VSCode is a folder-based editor, it does not require project files like some larger IDE’s such as visual studio. On the left hand side you should see a tree view of the folders in your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*pgVLCbFajv8e31mIERu0uw.png" /></figure><p>Expand the src folder and click on App.vue, this should open the file in the right-hand pane. You should also have received a recommendation popup from VSCode prompting you to install the Vetur extension.</p><p><a href="https://marketplace.visualstudio.com/items?itemName=octref.vetur">Vetur</a> is an amazing extension for VSCode, it gives the following for your Vue single-file components:</p><ul><li>Syntax-highlighting</li><li>Snippet</li><li>Emmet</li><li>Linting / Error Checking</li><li>Formatting</li><li>Auto Completion</li><li>Debugging</li></ul><p>So click on install and the extensions tab will open and Vetur should install, once that is done there should be a blue reload button next to the Vetur icon, click this and this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7791p6v_dqI1fTeNbixNw.png" /></figure><p>becomes this!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_q3RdsP7WdH3kV6mdjHVA.png" /></figure><p>All the html, javascript and css code is transformed from plain grey to beautiful syntax-highlighted colour.</p><p>VSCode has a plethora of extensions for working with javascript, css and other web components, and it is extremely configurable.</p><p>Now, go back to your console and start up the server again:</p><pre>npm run dev</pre><p>The vue-cli has configured hot module reloading as part of the web server install, this means that you can change your application in VSCode and these changes should be visible immediately in your browser.</p><p>Try it now, in App.vue, find the line that sets the msg data field and change it to something else:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*wVBOoBfg-wPm1joxE7nYug.png" /></figure><p>Go to your browser and the message should already be updated without the need to restart your server.</p><h3>What next?</h3><p>You now have a working environment for creating a web application with Vue.js. To continue this journey there are loads of excellent resources available online. The vue documentation is full of helpful examples, there are tutorials available on <a href="https://www.youtube.com/playlist?list=PL-lxoPS_1OXXgkRyuBa09fLj19mLwzidj">youtube</a> and <a href="https://www.udemy.com/vuejs-2-the-complete-guide/">udemy</a> and there are friendly, approachable people on <a href="https://twitter.com/sarah_edo?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">social</a> <a href="https://twitter.com/vuejs?lang=en">media</a> who love to share their experiences with Vue.js.</p><p>I hope this article was useful, it is my first attempt at writing about coding and would love any feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6990f92e918a" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/getting-started-vue-js-and-visual-studio-code-6990f92e918a">Getting Started: Vue.js and Visual Studio Code</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>