Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy from node_modules just the files needed for distribution using grunt and grunt-contrib-copy

I though I read somewhere that the "main" property of package.json could be used to copy just the files needed for "dist" or deployment. I supposed there was a grunt task for it, but I don't see anything that would help me or instruct me. I now copy everything under node_modules, but I certainly don't need to distribute library sample code, for example.

Is there a grunt task or any instructions on how to properly use grunt-contrib-copy to just copy the files from a node_module dependency hopefully from the config object's standard pkg object (a parsed package.json file)?

like image 414
Kenneth Brubaker Avatar asked Aug 15 '13 03:08

Kenneth Brubaker


2 Answers

package.json doesn't contain enough information for you to know what to include. You would have to parse out all the require statements, but even then there are cases you can't detect, like a module loading resources, etc.

The right way to do this is for package authors to ignore the files that isn't needed using a .npmignore file or even better, use the files property in package.json to explicitly define what files should be included in the package.

Unfortunately though, most package authors are lazy and don't bother with any of this...

I would encourage you to open PRs on the modules in question with the files property.

like image 102
Sindre Sorhus Avatar answered Nov 14 '22 08:11

Sindre Sorhus


You can:

1) Use copy task to copy each relevant file to dest directory:

copy:
  js:
    files: [
      { 
         expand: true, 
         cwd: 'node_modules/jquery', 
         src: 'jquery.min.js', 
         dest: 'www/js' 
      },
      { 
         expand: true, 
         cwd: 'node_modules/jquery-mobile-bower/js', 
         src: 'jquery.mobile-*.min.js', 
         dest: 'www/js' 
      }
    ]

jquery.min.js and jquery.mobile-x.y.z.min.js will be both copied to www/js directory.

2) Use concat task to concat all files to a single dest file (usefull to generate unique javascript / stylesheets files)

concat:
  options:
    separator: ';'
  js:
    dest: 'www/js/lib.js'
    src: [
      'node_modules/jquery/jquery.min.js',
      'node_modules/jquery-mobile-bower/js/jquery.mobile-*.min.js'
    ]

jquery.min.js and jquery.mobile-x.y.z.min.js will be merged into a single www/js/lib.js file, separated by a semicolon.

like image 21
Fábio Miranda Avatar answered Nov 14 '22 08:11

Fábio Miranda