Jason Rowe

Be curious! Choose your own adventure.

Getting started with Vue.js and NET Core

In this post, I’ll go over one option for getting started with Vue.js and .NET Core. I’ll go over how to generate a sample project via JavaScriptServices and point out how it gives you development and build tooling.

Microsoft ASPNET/JavaScriptServices

JavaScriptServices is a great option if you’re more familiar with .NET then node.js. I’ve used this template for a dashboard type application. I found it really easy to use to get a simpler SPA app setup and running quickly. I first learned about it via ASP.NET Community Standup – July 12th, 2016 – Steve Sanderson. If this sounds like something you would be interested in follow the steps below to try it out.

If you want to skip generating the project you can use Mark Pieszak’s project.ASP .NET Vue Starter.

Generate Sample Project

Prerequisites:

  • .NET Core SDK – Run the following to check if it is installed.
    dotnet --version
  • Node.js. – Run the following to check if it is installed. npm -v
  1. First run ‘dotnet new’ to view what templates you have available. If you don’t see Vue.JS template run the following to install:
    dotnet new --install Microsoft.AspNetCore.SpaTemplates
  2. In a folder for your project (example ‘helloworld’) run ‘dotnet new vue’
  3. Now you will have a sample Vue.JS project generated with a .csproj file that can be opened via Visual Studio or just open the folder to use Visual Studio Code. For people from traditional .NET background you will most likely be adding this .csproj file to a .sln file eventually.

Run the sample project.

Now that the sample project is generated you can change into the folder via a command prompt and run ‘dotnet run’. You should see something like the following:

C:\samples\helloworld>dotnet run
Using launch settings from C:\samples\helloworld\Properties\launchSettings.json...
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using 'C:\Users\jason.rowe\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
Hosting environment: Development
Content root path: C:\samples\helloworld
Now listening on: http://localhost:60391
Application started. Press Ctrl+C to shut down.
info: Microsoft.AspNetCore.NodeServices[0]
      webpack built a78c96051bca1cd55a84 in 5547ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:60391/

My app happened to startup on ‘http://localhost:60391/’ but check the logs for yours. Open up the site in a browser. Then in the code open the file in “ClientApp\components\home\home.vue.html” with an editor. Change some of the text and the browser should auto refresh with your changes. So how does that work?

Lets start by looking at the “Startup.cs” file:

This is where the hot module replacement magic happens that you just witnessed.

           if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

Notice this only runs for development purposes. During production the Vue project needs to be compiled via webpack during your build and output to the correct place. You can try this out via doing a dotnet publish.

C:\samples\helloworld>dotnet publish
Microsoft (R) Build Engine version 15.4.8.50001 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  helloworld -> C:\samples\helloworld\bin\Debug\netcoreapp2.0\helloworld.dll
  npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
  npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
  Hash: c407fb26a4b20940f64d
  Version: webpack 2.6.1
  Child
      Hash: c407fb26a4b20940f64d
      Time: 11309ms
                                     Asset    Size  Chunks                    Chunk Names
      89889688147bd7575d6327160d64e760.svg  109 kB          [emitted]
                                 vendor.js  218 kB       0  [emitted]         vendor
                                vendor.css  284 kB       0  [emitted]  [big]  vendor
  Hash: cc1e90038cc6288cebbb
  Version: webpack 2.6.1
  Child
      Hash: cc1e90038cc6288cebbb
      Time: 3129ms
         Asset      Size  Chunks             Chunk Names
       main.js   31.6 kB       0  [emitted]  main
      site.css  48 bytes       0  [emitted]  main
  helloworld -> C:\samples\helloworld\bin\Debug\netcoreapp2.0\publish\

Notice webpack ran and output the files correctly into a published folder for you. How did that happen? Open up the ‘helloworld.csproj’ file. The following section is what makes the webpack and npm install work during dotnet publish.

<Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
    <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
    <Exec Command="npm install" />
    <Exec Command="node node_modules/webpack/bin/webpack.js --config webpack.config.vendor.js --env.prod" />
    <Exec Command="node node_modules/webpack/bin/webpack.js --env.prod" />

    <!-- Include the newly-built files in the publish output -->
    <ItemGroup>
      <DistFiles Include="wwwroot\dist\**" />
      <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
        <RelativePath>%(DistFiles.Identity)</RelativePath>
        <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
      </ResolvedFileToPublish>
    </ItemGroup>
  </Target>

The biggest reasons this template worked for me was the ease of getting started. The only major downside is you can’t do some of the more advanced things if you use node.js during development. So if you have a simpler SPA project in mind and you like .NET Core this might be a good option for you.


Posted

in

,

by

Tags:

Comments

One response to “Getting started with Vue.js and NET Core”

  1. Noah Caron Avatar
    Noah Caron

    This is really nice helpful article.

    I noticed a few things as I worked through it.:

    1.) The command to install the template should have a double dash like this:

    dotnet new –install Microsoft.AspNetCore.SpaTemplates

    2.) The project I created off the template didn’t initially run for me because the node_modules folder was missing. After I expanded the Dependencies tree node in the project and right clicked on npm and chose Restore Packages, it generated the node_modules folder and it all built and ran fine.

Leave a Reply

Your email address will not be published. Required fields are marked *