实现 node_modules 共享

Gruntjs 做为前端工程化工具,可以很好的对前端资源进行管理(校验,合并,压缩)。前端

久之,发现一个问题node

npm install

每次不一样的项目都必须使用以上命令初始化,获取相对应的依赖模块,而这些模块每每都是类似。linux

那么,可否多个项目共用同个 node_modules ,作到一处管理,多处复用呢?npm

咱们尝试一下:json

咱们事先初始化一个 node_modules 目录,包含 grunt 等众多精彩使用到的模块segmentfault

node_modules

接着,咱们分析一下 grunt 模块下的 task.js 文件,能够找到两处任务加载的执行函数:windows

// Load tasks and handlers from a given directory.
task.loadTasks = function(taskdir) {}

// Load tasks and handlers from a given locally-installed Npm module (installed relative to the base dir).
task.loadNpmTasks = function(name) {}

从代码的注释能够获知前端工程化

task.loadTasks 方法能够从指定的目录加载任务模块
task.loadNpmTasks 方法则根据当前项目下 Npm module 所在的安装目录来加载任务模块函数

至此,咱们很快能够得到共享 node_modulse 的灵感,只要稍微改造一下 Gruntfile.js 文件,咱们就能够实现以前的想法了。grunt

// 引入 path 模块
var path = require('path');

module.exports = function(grunt) {

    // 从新设置 grunt 的项目路径,获取当前的 package.json 文件信息
    grunt.file.setBase(__dirname);

    // 获取当前目录相对于共享 node_modules 目录的路径(以windows下面为例)
    var nodepath = path.relative(__dirname,'D:/node_modules/') 

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        concat: "",
        uglify: "",
        clean : ""
    })

    // 加载任务
    grunt.task.loadTasks(path.join(nodepath,"grunt-contrib-clean",'tasks'));
    grunt.task.loadTasks(path.join(nodepath,"grunt-contrib-uglify",'tasks'));
    grunt.task.loadTasks(path.join(nodepath,"grunt-contrib-concat",'tasks'));

    // 注册任务
    grunt.registerTask('build', ['concat','uglify','clean']);
}

Made it!! 如获至宝,立刻命令行执行 grunt build。 吶呢,出错啦:

Fatal error: Unable to find local grunt.

出错的缘由也比较简单,咱们把 grunt 的目录给忽略了,所以在必须在执行命令的时候告诉 grunt 目录的位置,加上 --base 参数,就能成功运行了。

grunt build --base = d:\node_modules\

由于咱们这里人为的加上 --base 参数,改变了当前项目下 grunt 目录地址,在运行任务的时候,须要从新设置回去,这也解释了为何须要在 Gruntfile.js 加上如下代码:

grunt.file.setBase(__dirname);

PS: 以上为 windows 下的实现方法,最好把共享的 node_modules 和项目放置在同一分区,否则会出现文件路径不兼容的问题,Unix 和 linux 没有分区的概念,因此没有问题,其余的设置都同样。

The End, Enjoy it!

相关文章
相关标签/搜索