Integrating Node.JS, NPM and RequireJS into Visual Studio / MSBuild

Working at Deepend has exposed me to many new technologies which were out-of-scope for the projects I was involved in in my previous jobs.

In my current project, we’re using RequireJS, along with their supplied optimizer to minify, and uglify our solution. To achieve this, we are required to execute the compiler via node.js.

In an attempt to streamline this process, I’ve built upon the NuGet package manager’s solution for automatic download and installation of packages, and have it running successfully with Node.

Here’s a brief rundown of the steps involved:

  1. Create a .node folder in your solution root
  2. Place my custom node.targets file inside the .node folder
  3. Open your project file in a text-editor and add the following lines:
    <Import Project="$(SolutionDir)\.node\Node.targets" Condition="Exists('$(SolutionDir)\.node\Node.targets')" />
    <Target Name="BeforeBuild">
      <CallTarget Targets="CheckNodePrerequisites;RestoreNodePackages" />
    </Target>
  4. Download the latest npm package
  5. Extract the node_modules folder to your solution root
  6. Check files into source control, and optionally create any .gitignore or similar files to ignore all other packages placed inside node_modules folders
  7. When you build, your project should now automatically download node.exe into your .node folder

You are now free to use NPM to install packages into your project as normal, e.g.

npm init
npm install requirejs --save

If you need to execute any packages explicitly, you can add pre and post-build events to your project configuration, e.g.

"$(SolutionDir).node\node.exe" "$(ProjectDir)node_modules\requirejs\bin\r.js" -o "$(ProjectDir)\static\js\main.build.js"
"$(ProjectDir)\Deepend.ProjectSync.exe" $(ProjectDir)

These instructions should work for both packaged, and shrink-wrapped installs. I’ve only tested on packaged installations myself so far.

Next I’ll be working on getting NPM to come down automatically with node, and updating my ProjectSync tool to support insertion of node and other additional targets into project files, so this whole process will become automatic once you run ProjectSync once.

This of course is just the tip of the iceberg. I’ve now cloned the nuget project, and plan to modify and distribute a version that adds node package manager support direct to visual studio as a proper extension.

One thought on “Integrating Node.JS, NPM and RequireJS into Visual Studio / MSBuild

Leave a Reply

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