0

I have created a JavaScript library module using browserify --standalone which works find with npm test. I am trying to create a demo application that uses the library module in the browser. npm update installs the library module under node_modules/library/blah.js. I can set the demo application to server the library to the browser from that location and everything works fine. I would rather have a command that copies (and ideally renames) the file from that location into a top level folder. Then the library model would be a plain old js file for the demo app. What is the simplest way to do this?


update: The reason that I would like to copy and rename the library file is so it can be easily used with other technologies that like to zip up all the js files to deploy them to a web server.

simbo1905
  • 6,321
  • 5
  • 58
  • 86

1 Answers1

0

A related question is How to use npm with ASP.NET Core which is asking how to use JavaScript installed using npm install within a web application that expects browser JavaScript to be in the folder wwwroot. I am not actually using ASP.NET but it proves the point that someone wanting to use my npm library code in the browser might want to copy library files from the npm install folder node_modules into some other folder visible to the browser.

The accepted answer over there suggests to use gulp to copy files. It asserts that gulp is the "task runner of choice for VS (visual studio)". There are a lot of other task runners so you can pick your own. A quick look around at gulp examples I eventually came up this gist that IMHO looks very clear and practical.

This lead to me add the following lines to my package.json which has npm run gulp whenever npm install is run:

  "scripts": {
    "prepare": "gulp minify"
  }, 

Then created a stripped own version of the gist as gulpfile.js to copies the library file into the top level folder and rename its extension to say which library the file came from:

"use strict";

var _      = require('lodash'),
    gulp   = require('gulp'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename');

var js = [
    './node_modules/thinbus-srp/browser.js'
];

gulp.task('copy-min-js', function () {
    _.forEach(js, function (file, _) {
        gulp.src(file)
            .pipe(uglify())
            .pipe(rename({ extname: '.thinbus.js' }))
            .pipe(gulp.dest('.'))
    });
});

gulp.task('minify', ['copy-min-js']);

This means that any time I update the library using npm install the latest library file is copied and renamed into the top level folder were the browser can load it.

simbo1905
  • 6,321
  • 5
  • 58
  • 86