Andy J Andy J - 10 months ago 74
Node.js Question

Is there a way to automatically copy files to wwwroot?

I have my index.html in the directory called wwwroot and it's being accessed from the browser on locahost:5001. Whe nI installed some packages using NPM, the directory node_modules was placed on the same level as wwwroot.

When I'm linking to the files, I use a relative path like this.


It seems to me that a better approach would be to have those delivered to the wwwroot directory and have them reside there. Not all the contents of the packages, just the files that are actually being used (skipping readmes etc.).

Is there a package for that? Or is it something that needs to be done using a build script?

Answer Source

You are not supposed to access node_modules files from front-end like your html or cshtml files. So you are right you should copy them to the wwwroot folder.

You can use grunt as linked in Tseng comment but I personally prefer Gulp, I think it's much quicker and easier to use.

Your package.json file:

    "version": "1.0.0",
    "name": "",
    "private": true,
    "devDependencies": {
        "gulp": "3.9.1",
        "gulp-cached": "1.1.0",

Then create a gulpfile.js at your project's root level and you can write something like

var gulp = require('gulp'),
cache = require('gulp-cached'); //If cached version identical to current file then it doesn't pass it downstream so this file won't be copied 

gulp.task('default', 'copy-files');

gulp.task('copy-node_modules', function () {

try {

    catch (e) {
        return -1;
    return 0;

Finally open the Task Runner Explorer (if you are using Visual Studio) and execute either your default task or directly the copy-node_modules task.

Gulp is very useful, I suggest you explore other different gulp tasks. You can concat and minify both CSS and JS files, remove comments, you can even create a watch task that executes other tasks as soon as a file changes.