Andy J Andy J - 20 days ago 6
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.


href="../node_modules/package_this_or_that/package.min.js"


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

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": "asp.net",
    "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 {

    gulp.src('node_modules/**')
        .pipe(cache('node_modules'))
        .pipe(gulp.dest('wwwroot/node_modules'));
    }
    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.

Comments