Blog

Debugging VueJS + TypeScript with VS Code - Part 2

In the past I have written about how to setup VS Code to debug a VueJS + TypeScript project. Since writing that article it's a method I've continued to use and it works well. It's quick to spin up and quite reliably allows you to place breakpoints in code.

However one aspect of it that I don't like is it's not so much "Run and Debug" from VSCode, it's more just the debug part, as to use it you must first go to a terminal and run your VueJS application.

There's two problems with this:

1. Most of the time you will just run the application not debugging (because why debug when you don't have an issue), therefore when you need it, you have to redo what you just did that caused an error. Instinctively there is then a desire to guess at what was wrong rather than going to the extra effort of debugging (frequently when you do this your guess is wrong and you end up spending more time guessing at what was wrong than using the tool that will tell you).

2. As the debugger generally isn't running, exceptions never get flagged up, and unless you have the browser console open (and check it), you can remain oblivious to something going wrong in your app.

There is a solution though, and it's quite simple!

Using VS Code to launch via npm

First follow through my previous guide on debugging a VueJS and TypeScript application.

Next, in your launch.config file add a new configuration with the definition below. This will run the command in a debug terminal, effectively doing the same thing as you typing npm run serve.

{
    "command": "npm run serve",
    "name": "Run npm serve",
    "request": "launch",
    "type": "node-terminal"
  },

To get both our new and old configuration to run you can add a compound definition, that does both at the same time.

Here's mine.

"compounds": [
  {
    "name": "Run and Debug",
    "configurations": ["Run npm serve", "vuejs: edge"]
  }
],

My complete file now looks like this. Note you don't need configurations for edge and chrome, just use the one for the browser you use.

{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"compounds": [
  {
    "name": "Run and Debug",
    "configurations": ["Run npm serve", "vuejs: edge"]
  }
],
"configurations": [
  {
    "command": "npm run serve",
    "name": "Run npm serve",
    "request": "launch",
    "type": "node-terminal"
  },
  {
    "type": "pwa-msedge",
    "request": "launch",
    "name": "vuejs: edge",
    "url": "http://localhost:8080",
    "webRoot": "${workspaceFolder}",
    "breakOnLoad": true,
    "sourceMapPathOverrides": {
      "webpack:///./*": "${webRoot}/*"
    },
    "skipFiles": ["${workspaceFolder}/node_modules/**/*"]
  },
  {
    "type": "chrome",
    "request": "launch",
    "name": "vuejs: chrome",
    "url": "http://localhost:8080",
    "webRoot": "${workspaceFolder}",
    "breakOnLoad": true,
    "sourceMapPathOverrides": {
      "webpack:///./*": "${webRoot}/*"
    },
    "skipFiles": ["${workspaceFolder}/node_modules/**/*"]
  }
]
}

Now whenever you want to run the application, just run the compound Run and Debug and your VueJS app will start up and launch in your browser.

Reducing the size of Sitecore Master DB

When it comes to Sitecore development, an issue every developer has likely experienced is the size of the databases in relation to the size of their hard disk. In an ideal world production DBs would contain production data, test environments would have data ideally suited for testing and developer workstation would have the minimum required to develop the solution.

In reality though, I think most people have the experience of everything being a copy from production. This ends up being the case due to a clients requirements that UAT needs to looks the same as prod, QA needs prod content to replicate a bug and although critical Sitecore items may have been serialized, not having any content in your local makes it a bit hard to dev.

When a website is new and doesn't have much content this isn't a huge issue, but when you inherit one 5 years old with a 25gb DB, things start to become a problem. Not only is the hard disc space required an issue, but just setting a new developer up takes hours from download times.

After getting a new laptop and being faced with the challenge of needing to copy multiple DBs (and not even having enough space to back them up on my existing machine), I decided to finally do something about reducing the size of them,

Removing old item versions

Having a history of item versions is a great feature for content editors, however as a dev I don't really need them on my local. They also hold references to media items that aren't used any more.

This Sitecore Powershell script from Webbson does exactly that and even lets your specify how many version you want to keep. I went for 1.

<#
This script will remove old versions of items in all languages so that the items only contains a selected number of versions.
#>

$item = Get-Item -Path "master:\content"
$dialogProps = @{
  Parameters = @(
      @{ Name = "item"; Title="Branch to analyse"; Root="/sitecore/content/Home"},
      @{ Name = "count"; Value=10; Title="Max number of versions";  Editor="number"},
      @{ Name = "remove"; Value=$False; Title="Do you wish to remove items?"; Editor="check"}
  )
  Title = "Limit item version count"
  Description = "Sitecore recommends keeping 10 or fewer versions on any item, but policy may dictate this to be a higher number."
  Width = 500
  Height = 280
  OkButtonName = "Proceed"
  CancelButtonName = "Abort"
}

$result = Read-Variable @dialogProps 

if($result -ne "ok") {
  Close-Window
  Exit
}

$items = @()
Get-Item -Path master: -ID $item.ID -Language * | ForEach-Object { $items += @($_) + @(($_.Axes.GetDescendants())) | Where-Object { $_.Versions.Count -gt $count } | Initialize-Item }
$ritems = @()
$items | ForEach-Object {
  $webVersion = Get-Item -Path web: -ID $_.ID -Language $_.Language
  if ($webVersion) {
      $minVersion = $webVersion.Version.Number - $count
      $ritems += Get-Item -Path master: -ID $_.ID -Language $_.Language -Version * | Where-Object { $_.Version.Number -le $minVersion }
  }
}
if ($remove) {
  $toRemove = $ritems.Count
  $ritems | ForEach-Object {
      $_ | Remove-ItemVersion
  }
  Show-Alert "Removed $toRemove versions"
} else {
  $reportProps = @{
      Property = @(
          "DisplayName",
          @{Name="Version"; Expression={$_.Version}},
          @{Name="Path"; Expression={$_.ItemPath}},
          @{Name="Language"; Expression={$_.Language}}
      )
      Title = "Versions proposed to remove"
      InfoTitle = "Sitecore recommendation: Limit the number of versions of any item to the fewest possible."
      InfoDescription = "The report shows all items that have more than <b>$count versions</b>."
  }
  $ritems | Show-ListView @reportProps
}

Close-Window

Removing unpublished items

After a few failed attempts at reducing the size of the DB's, I discovered that the content editors working on the website had seemingly never deleted any content. Instead that had just marked things as unpublishable. I can see the logic in this, but after 5+ years, they have a lot of unpublished content filling up the content tree.

Well if it's unpublished I probably don't need it on my local machine so lets delete it.

Here's a script I wrote, the first part removes items set to never publish. After running just this part I found lots of the content items had the item set to publish but the version set to hidden. The second part loops through versions on items and removes any version set to hidden. If the item has no version left then it is removed too.

// Remove items set to never publish
Get-ChildItem -Path "master:\sitecore\content" -Recurse | 
Where-Object { $_."__Never publish" -eq "1" } | Remove-Item -Recurse -Force -Confirm:$false
  
// Loop through items and remove versions set to never publish, then remove the item if it has no versions left
foreach($item in Get-ChildItem -Path "master:\sitecore\content" -Recurse) {

$item
foreach ($version in $item.Versions.GetVersions($true))
{
   $version
      $version."__Hide version"
      if ($version."__Hide version" -eq "1" ) {
          $version| Remove-ItemVersion -Recurse  -Confirm:$false
      }
}

if ($item.Versions.GetVersions($true).count -eq 0) {
   $item | Remove-Item -Recurse -Force -Confirm:$false
}
}

Remove dead links

In the next step I rebuild the links DB, but I kept ending up with entries in the link table with target items that didn't exist. After a bit of searching I came across an admin page for clearing up dead links.

/sitecore/admin/RemoveBrokenLinks.aspx

With this page you can remove all those pesky dead links caused by editors deleting items and leaving the links behind.

Remove broken links screen in Sitecore

Clean Up DBs

With our content reduced the DB's now need a clean up before we do anything else.

In the admin section there is a DB Cleanup page that will let you perform various tasks on the DB. I suggest doing all of these.

/sitecore/admin/DBCleanup.aspx

Sitecore Database cleanup page

Once this is done navigate to the control panel and rebuild the link database. From the control panel you can also run the clean up database script, but it won't give you as much feedback.

/sitecore/client/Applications/ControlPanel.aspx?sc_bw=1

Sitecore rebuild link database screen

Remove unused media

With all the old versions/items/dead links removed and the DB's cleaned up its time to get rid of any unused media items. It's likely if you have a large DB that most of the space will be taken up by the media items. Fortunately with another PowerShell script we can removed any media that isn't linked too.

This PowerShell script is an adapted version of one by Michael West. You can find his version here https://michaellwest.blogspot.com/2014/10/sitecore-powershell-extensions-tip.html?_sm_au_=iVVB4RsPtStf5MfN

The main difference is I've been more aggressive and removed the checks on item owner and age.

filter Skip-MissingReference {
  $linkDb = [Sitecore.Globals]::LinkDatabase
  if($linkDb.GetReferrerCount($_) -eq 0) {
      $_
  }
}

$items = Get-ChildItem -Path "master:\sitecore\media library" -Recurse | 
  Where-Object { $_.TemplateID -ne [Sitecore.TemplateIDs]::MediaFolder } |
  Skip-MissingReference

if($items) {
  Write-Log "Removing $($items.Length) item(s)."
  $items | Remove-Item
}

Shrink databases

Lastly through SQL management studio, shrink your database and files to recover unused space you hopefully now have from removing all of that media.

In my case I was able to turn a 20+ GB database into a 7 GB database by doing these steps.

If your local is running with both web and master DB, you should now do a full publish. The item versions which are published should stay exactly the same as we only removed items set to not publish. You should however get a reduction in your web DB from the media items being removed.

Which JavaScript for loop should I use?

When given a choice of 4 seemingly different ways to do the same thing, I've always been the person that wants to know what the difference is? To often we can blindly write code the way the person before us did and not understand the reason to do it a certain way, but what if the scenario has changed. When multiple options exist there's usually a reason why. It can be a language style improvement to make things easier to write, but more often than not there's a fundamental difference in what it actually does.

So, for loops, four seems like a lot, gotta be some differences right?

for

This is likely to be the first type of for loop you encounter when learning to program. It's a very manual type of loop where you create a initial expression, a condition expression to keep running the loop and an increment expression.

for (let i = 0; i < 5; i++) {
  console.log(i);
}

// Result:
// 0
// 1
// 2
// 3
// 4

The big downside of the for loop is it doesn't actually loop through a collection. e.g. If you had an array and wanted to loop through each of it's objects you could do this as follows:

const arr = ['a', 'b', 'c'];

for (let i = 0; i < arr.length; ++i) {
  console.log(arr[i]);
}

In effect the loop is incrementing a number and you then use that number to access the position of the array. The result is you have more code to write that isn't serving any real purpose.

However as this is a much more manual loop process you have far more control over the loop. e.g.

  • You could increment by a different number.
  • You could go backwards.
  • The condition might not be linked to the length of an array.
  • You might not even be looping through an array.

Pros

  • Potentially faster in performance.
  • Break statement can be used to come out of the loop.
  • It works with the await keyword.
  • Not just for looping through arrays.

Cons

  • Not as readable as others.
  • You have more code to write.

for...in

You probably don't want this one. Here's an example:

const arr = ['a', 'b', 'c'];

for (const i in arr) {
  console.log(arr[i]);
}

// Result:
// "a"
// "b"
// "c"

Although we're now specifically looping through a collection like an array and don't need to do all of that i < array.length stuff, what we're given isn't the object in the array but a property name to access it on the object.

Here's another example:

const arr = ['a', 'b', 'c'];
arr.foo = 'John'

for (const i in arr) {
  console.log(arr[i]);
}

// Result:
// "a"
// "b"
// "c"
// "John"

That looks a bit weird! The for...in loop doesn't just loop through an array, it loops through an objects enumerable properties, which could be the items in an array, but it could be other stuff too.

For this reason, unless your doing something quite niche its probably not the loop you are looking for and is likely to cause you an issue which your objects has one more property than you were expecting.

Pros

  • Can loop through all the enumerable properties on an object.

Cons

  • Looping through all the properties of an object isn't likely what you want.

forEach

As the name implies, a for each loop will iterate through each element in an array. Here's an example:

const arr = ['a', 'b', 'c'];

arr.forEach((i) => {
  console.log(i);
})

// Result:
// "a"
// "b"
// "c"

The forEach function takes an anonymous function as a parameter and will then call that function for each object in the array, passing in the object from the array.

This offers a big improvement over the initial for loop as we have a lot less code to write and we're actually given the object rather than a variable to go an find it.

However there are some downsides due to it effectively being a function call passing an anonymous function to execute.

Firstly you can't stop the forEach part way through. With the others you can use the break keyword to stop the iteration.

Secondly there's added confusion around the scope of what this is. Assuming your function is in a class, unless you use the arrow syntax (as in the example) you won't be able to access any of the other functions in your class as passing a regular function would change the scope.

// This works
class foo
{
myFunction() {
  const arr = ['a', 'b', 'c'];

  arr.forEach((i) => {
    this.outputValue(i)
  })
}

outputValue(x) {
  console.log(x);
}
}

// This Doesn't
class foo
{
myFunction() {
  const arr = ['a', 'b', 'c'];

  arr.forEach(function(i) {
    this.outputValue(i)
  })
}

outputValue(x) {
  console.log(x);
}
}

You also can't use an await within the foreach loop. e.g.

async function run() {
const arr = ['a', 'b', 'c'];
arr.forEach(el => {
  // SyntaxError
  await new Promise(resolve => setTimeout(resolve, 1000));
  console.log(el);
});
}

Pros

  • Much shorter to write and easier to read.
  • Iterator provides the object from the array.

Cons

  • Easy to mess up context of this.
  • No way to break the loop.
  • Async/Await doesn't work on functions within the loop.
  • Can only loop through arrays.
  • It's performance is slower (nice article here comparing the performance differences), not to such an extent it would matter on a small object, but large objects could start to take a hit.

for...of

When looping through an array, the for...of loop combines the best of all the other loops. It has the same simple syntax of the for...in loop but instead of enumerating over enumerable properties, it loops through the iterable objects such as the items in an array.

Like the forEach loop you are provided with the object in the array rather than it's index or property name.

const arr = ['a', 'b', 'c'];

for (const i of arr) {
  console.log(i);
}

// Result:
// "a"
// "b"
// "c"

You can also break the loop and access properties outside of the loop.

const stopValue = 'b'
const arr = ['a', 'b', 'c'];

for (const i of arr) {
  console.log(i);
  if (i == stopValue)
      break;
}

// Result:
// "a"
// "b"

Pros

  • Lowest amount of extra code to write.
  • Iterator provides the object.
  • Doesn't use an anonymous function so scope doesn't change.
  • Loop can be stopped as needed.
  • Async still works.
  • Works with more than just arrays.

Cons

  • Have to be looping over the iterable items in an object.
  • Can't easily access the index value.

Conclusion

If you want to iterate through something like an array, for...of would be my recommendation to use. A for...in loop is likely to be less relevant but has its place, and for all other loops which don't relate to the objects in an array a good old for loop still has it's place.