{"id":13659342,"url":"https://github.com/cmtt/gulp-di","last_synced_at":"2025-04-24T14:33:12.591Z","repository":{"id":51554991,"uuid":"48115294","full_name":"cmtt/gulp-di","owner":"cmtt","description":"gulp-di is a dependency injection framework for the Gulp streaming build system.","archived":true,"fork":false,"pushed_at":"2021-08-11T17:58:59.000Z","size":521,"stargazers_count":42,"open_issues_count":5,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-20T00:39:02.496Z","etag":null,"topics":["dependency-injection","gulp-plugins","javascript","javascript-dependency-injection"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cmtt.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-12-16T14:32:03.000Z","updated_at":"2025-03-08T20:03:59.000Z","dependencies_parsed_at":"2022-08-19T22:40:39.534Z","dependency_job_id":null,"html_url":"https://github.com/cmtt/gulp-di","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmtt%2Fgulp-di","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmtt%2Fgulp-di/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmtt%2Fgulp-di/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmtt%2Fgulp-di/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cmtt","download_url":"https://codeload.github.com/cmtt/gulp-di/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250643697,"owners_count":21464220,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dependency-injection","gulp-plugins","javascript","javascript-dependency-injection"],"created_at":"2024-08-02T05:01:07.694Z","updated_at":"2025-04-24T14:33:12.271Z","avatar_url":"https://github.com/cmtt.png","language":"JavaScript","readme":"# [gulp](http://gulpjs.com)-di\n\n\u003ca href=\"http://gulpjs.com\"\u003e\n  \u003cimg align=\"right\" height=\"192\" src=\"http://cmtt.github.io/gulp-di/src/gulp.png\"\u003e\n\u003c/a\u003e\n\n\u003cdiv\u003e\n  \u003ca href=\"https://travis-ci.org/cmtt/gulp-di\"\u003e\n    \u003cimg src=\"https://img.shields.io/travis/cmtt/gulp-di/master.svg?style=flat-square\" alt=\"Build Status\"\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://www.npmjs.org/package/gulp-di\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/v/gulp-di.svg?style=flat-square\" alt=\"npm version\"\u003e\n  \u003c/a\u003e\n  \u003ca href=\"http://spdx.org/licenses/MIT\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/l/gulp-di.svg?style=flat-square\" alt=\"npm licence\"\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://coveralls.io/github/cmtt/gulp-di\"\u003e\n    \u003cimg src=\"https://img.shields.io/coveralls/cmtt/gulp-di/master.svg?style=flat-square\" alt=\"Code coverage\"\u003e\n  \u003c/a\u003e\n  \u003ca href=\"http://www.ecma-international.org/ecma-262/6.0/\"\u003e\n    \u003cimg src=\"https://img.shields.io/badge/ES-2015-F0DB4F.svg?style=flat-square\" alt=\"ECMAScript 2015\"\u003e\n  \u003c/a\u003e\n\u003c/div\u003e\n\ngulp-di is a dependency injection framework for the [Gulp](http://gulpjs.com)\nstreaming build system.\n\n- Shrink your Gulpfile to less than ten lines.\n- Manage gulp plugins solely via npm and variables in your task module files.\n- No major refactoring required.\n\nSee below for further examples!\n\n## Installation\n\n````bash\n  $ npm install --save gulp-di\n````\n\n## Built-in dependencies\n\nYou can use the following dependencies in your modules and tasks.\n\n| Name         |  Type    |  Description                                  |\n|--------------|----------|-----------------------------------------------|\n| _            | Function | [lodash](https://github.com/lodash/lodash)    |\n| basePath     | Function | Resolves a path relative to your project path |\n| chalk        | Object   | [chalk](https://www.npmjs.com/package/chalk) for using colors when logging |\n| gulp         | Object   | The gulp instance                             |\n| gutil        | Object   | [gulp-util](https://www.npmjs.com/package/gulp-util) |\n| log          | Function | [gulp-util](https://www.npmjs.com/package/gulp-util)'s log |\n| Package      | Object   | package.json as object                        |\n| runningTasks | Array    | currently running gulp tasks (experimental)   |\n| taskInfo     | Object   | infos about task functions (experimental)     |\n\nIn addition, all Gulp modules which are installed in your package.json are\navailable in your modules, driven by [gulp-load-plugins](https://www.npmjs.com/package/gulp-load-plugins).\n\nFor example, if you install the \"gulp-concat\" as devDependency (in your\npackage.json) plugin using ...\n\n````bash\n  $ npm install --save-dev gulp-concat\n````\n\n... it will become available as dependency in each module file:\n\n````js\n// tasks/concat-texts.js\nmodule.exports = (gulp, concat) =\u003e {\n  /* Concatenates all *.txt files from src/ to public/result.txt */\n  return gulp.src('src/**/*.txt')\n  .pipe(concat('result.txt'))\n  .pipe(gulp.dest('public/'));\n};\n````\nPlease read the API notes below for configuring a pattern for packages which\ndo not start with \"gulp-\" or \"gulp.*\".\n\n## Example: Basic refactoring\n\nInstead of declaring all gulp tasks in a single file, gulp-di allows you to\ntake a more modular approach. You can separate your stream definitions from\nconfigurations while gulp-di handles the majority of your existing calls to\nrequire() for you.\n\nIn this example, we will see how we can move a call to gulp.task() to a\nseparate file.\n\nAdditionally, we will see how we can detach a constant (in this case: a glob\nmatching all files with the \"jpg\" extension) from the actual task.\n\nThe following task\n\n````js\n/* gulpfile.js (previous version) */\n\nconst gulp = require('gulp');\ngulp.task('images', () =\u003e {\n  return gulp.src('./**/*.jpg')\n  .pipe(gulp.dest('output/'));\n});\n````\n\nwould be re-factored to the file at tasks/images.js as following.\n\n````js\n/* tasks/images.js */\n\nmodule.exports = (gulp, imagesPath) =\u003e {\n  gulp.task('images', () =\u003e {\n    return gulp.src(imagesPath)\n    .pipe(gulp.dest('output/'));\n  });\n};\n````\n\nNotice that the function uses the \"imagePath\" constant. Such constants can\nbe defined in your Gulpfile files in order to separate them from the tasks.\n\nThus, you can now use all of your Functional programming skills with Gulp and\n**assemble** your tasks from other declarations and build much more\nflexible and re-usable tasks.\n\ngulp-di should help you to reduce your Gulpfile's complexity.\nIn this example, we will declare additionally the \"imagePath\" constant which is\nbeing used in our \"images\" task.\n\n````js\n/* gulpfile.js (refactored version) */\n\nconst gulp = require('gulp');\nlet di = require('gulp-di')(gulp);\n.tasks('./tasks')\n.provide('imagesPath', 'src/**/*.jpg')\n.resolve();\n````\n\nAdditionally, you can now \"inject\" arbitrary values into your functions, e. g.\nrun-time configurations, asynchronous methods for usage with Gulp's asynchronous\nAPI, constants etc.\n\nThe following example uses constants and modules in order to compose a helper\nfunction.\n\n````js\n/* gulpfile.js (refactored version) */\n\nconst gulp = require('gulp');\nlet di = require('gulp-di')(gulp);\n.tasks('./tasks')\n.provide('sourcePath', 'src')                    // Provide a string constant.\n.module('extensionPath', (sourcePath) =\u003e {       // Add a module providing a\n                                                 // helper function to get a\n                                                 // extension name.\n\n  return (extname) =\u003e `${sourcePath}/**/*.${extname}`;\n\n})\n.task(function (gulp, extensionPath) {\n  gulp.task('copy-images', function () {\n    // Copies all *.jpg images from src/ to public/\n    return gulp.src(extensionPath('jpg')).pipe(gulp.dest('public/'));\n  });\n})\n.resolve();\n````\n\n## API\n\n### GulpDI(_object_ gulp, _object_ options)\n\nCreates a new GulpDI instance. The first argument must always be the gulp\ninstance from your Gulpfile.\n\nIf you specify options, these will be passed to [gulp-load-plugins](https://www.npmjs.com/package/gulp-load-plugins) under the hood (\"camelize\" cannot be configured at the moment).\n\n```js\nconst gulp = require('gulp');\nlet di = GulpDI(gulp, {\n  DEBUG: false, // when set to true, the plugin will log info to console. Useful for bug reporting and issue debugging\n  pattern: ['gulp-*', 'gulp.*'], // the glob(s) to search for\n  config: 'package.json', // where to find the plugins, by default searched up from process.cwd()\n  scope: ['dependencies', 'devDependencies', 'peerDependencies'], // which keys in the config to look within\n  replaceString: /^gulp(-|\\.)/, // what to remove from the name of the module when adding it to the context\n  rename: {}, // a mapping of plugins to rename\n  renameFn: function (name) { ... } // a function to handle the renaming of plugins (the default works)\n});\n```\nThe following options are additionally available:\n\n| Name             |  Type    |  Description                                  |\n|------------------|----------|-----------------------------------------------|\n| DEBUG            | Boolean  | Whether to log debugging information or not   |\n| noBuiltin        | Boolean  | Disables helpers: basePath, log, Package      |\n| noHelp           | Boolean  | Toggles the \"help\" task/providing taskInfo    |\n| noModules        | Boolean  | Do not expose chalk, gutil and lodash (_)     |\n| noRunningTasks   | Boolean  | Do not provide the \"runningTasks\" function    |\n\n### Chainable methods\n\nThe following methods are chainable:\n\n#### .inject(_function_ fn, returnValue)\n\nExecutes code which depends on the current's instance dependencies.\nPlease note that you will have to resolve() your instance if you should depend\non anything else than payloads which have been initialized by provide().\n\nWhen returnValue is set, this method returns the return value of the injected\nfunction (e.g. the function is not chainable when set to true)\n\n````js\ndi.provide({ 'PI' : Math.PI, 'DEG_TO_RAD' : 180 / Math.PI });\nlet circle = di.inject(['PI','DEG_TO_RAD', (PI, DEG_TO_RAD) =\u003e {\n  return 2 * PI * DEG_TO_RAD;\n}], true);\nconsole.log(circle); // 360\n````\n\n#### .provide(_string_ name, _*_ payload)\n\nProvides a constant for further usage in modules and tasks. You can can also\nprovide a hashmap of constants as following:\n````js\ndi.provide({ 'PI' : Math.PI, 'SIN' : Math.sin });\n````\n\n#### .task(_function_ fn)\n\nAdds a task module. Add your provide()d dependencies to the function's argument\nlist to require a dependency. Their order does not matter.\n\nPlease note that tasks don't have names (in contrast to modules) as\nyou shouldn't depend on them using gulp-di. Use the \"deps\" array when calling\ngulp.task() instead in order to achieve a specific task execution order.\n\nYou can also use a hashmap as following:\n\n````js\ndi.task({\n  /* Copies all *.png images from src/ to public/ */\n  assets : (gulp) =\u003e gulp.src('src/**/*.png').pipe(gulp.dest('public/'))\n});\n````\n\n#### .module(_string_ name,_function_ fn)\n\nAdds a module with the given name. In contrast to a task, a module has a name\nand its return value will be provided - thus, modules can be injected into tasks\nas well as your constants.\n\nYou can provide a hashmap, too.\n\n#### .resolve()\n\nResolves all dependencies and runs all task modules. You need to call this\nmethod after your declarations.\n\n#### .tasks(_string_ directory)\n\nLoads all tasks from the specified directory, using [require-dir](https://www.npmjs.com/package/require-dir).\n\n#### .modules(_string_ directory)\n\nLoads all modules from the specified directory.\n\n#### .byId(_string_ name)\n\nReturns the specified dependency. When you are demanding modules, please keep in\nmind that you will need to call resolve() beforehand, otherwise, this would\nreturn your module function.\n\n## Using dependency injection in general\n\nBy design, dependency injection is opt-in for everything, thus you can use\ngulp-di for use cases beyond your gulp tasks.\n\n### Setting values\n\nWhen using DI, you can set values on your instance to arbitrary values. They\nwill become available in your module files.\n\n````js\nconst gulp = require('gulp');\nlet di = require('gulp-di')(gulp, { DEBUG: false });\ndi.provide('PI', Math.PI);\ndi.provide('RAD_TO_DEG', 180 / Math.PI);\n````\n\n### Declaring task modules\n\nYou can then declare a single function or a whole directory of\nCommonJS modules using the tasks() method.\n\n````js\ndi.task((PI, RAD_TO_DEG, basePath) =\u003e {\n  console.log((PI * 2 * RAD_TO_DEG) + '°');\n});\n````\n\nNote that you have access to the gulp-di instance in the task function's scope.\nYou could f.e. access the \"options\" object in your function as following:\n\n````js\ndi.task(() =\u003e {\n  if (this.options.DEBUG) { console.log('Debug is enabled'); }\n});\n````\n\n### Running all modules and resolving dependencies\n\nYou need to execute all provided values and modules by running resolve()\nafterwards.\n\nWhile you place calls to task(), tasks() and provide, the execution order of your\ndepends on the declared dependencies. With resolve(), the graph is being\nresolved and all modules are called with the provided values.\n\n````js\ndi.resolve();\n// logs 360°\n````\n\n## Experimental functionalities\n\nPlease use these features with caution for now.\n\n### gulp help\n\nThis example is included by default.\n\nAn included experiment uses the API to intersect all calls to gulp.task to\ncollect information about the tasks.\n\nIt registers a gulp \"help\" task which logs then all comments included in\ngulp.task. In addition, a \"taskInfo\" hashmap is available for injection. It\ncontains the information about your gulp tasks which is being also used by\nthe \"help\" task.\n\n````js\nconst gulpDi = require('gulp-di');\nlet di = gulpDi()\n.task(function (gulp, taskInfo, log, chalk) {\n  gulp.task('my-help', function () {\n    /* Logs basic information about tasks. */\n    for (let name in taskInfo) {\n      let entry = taskInfo[name];\n      log(chalk.magenta(name), 'with dependencies',  entry.deps);\n    }\n  });\n})\n.resolve();\n````\n### runningTasks\n\nThis function returns an array of strings, containing all current Gulp tasks,\nincluding dependencies.\n\n### Helper functions\n\nThe following functions are currently not integrated into gulp-di, but you can\nrequire them as following:\n\n````js\nconst getPath = require('gulp-di/contrib/get-path');\nconst standardTask = require('gulp-di/contrib/standard-task');\n````\n\n#### getPath(_string_ key)\n\nReturns a property specified by the given dot-delimited key:\n\n````js\nconst data = {\n  at : 1350506782000,\n  ids : ['507f1f77bcf86cd799439011', '507f191e810c19729de860ea']\n};\n\nlet PI = getPath(Math, 'PI');\nlet at = getPath(data, 'at'));\nlet firstId = getPath(data, 'ids.0');\n````\n\n#### standardTask(_string_ name, _string_ src, _string_ dest, ...)\n\nGenerates a default task, assuming you want to pipe _src_ through the plugin specified by _name_ to _dest_. All parameters following \"dest\" are serialized if necessary and passed\nto the plugin.\n\nUsing this method, you will just need to install a gulp plugin with npm and set\nup a task as following:\n\n````js\nlet taskFn = standardTask('jade', 'templates/**/*.jade', 'public', { pretty : false });\n\n// Register the task function\ndi.task(taskFn);\n\nconsole.log(taskFn.toString());\n\nfunction jadeTask(gulp, jade) {\n  /**\n   * Generated task function, registers a \"jade\" task.\n   * @param {object} gulp The current gulp instance\n   * @param {jade} jade The \"jade\" gulp plugin\n   */\n\n  gulp.task(\"jade\", () =\u003e {\n     /**\n      * jade task, declared at 10-contrib.js:44\n      */\n    return gulp.src(\"templates/**/*.jade\")\n    .pipe(jade({\"pretty\":false}))\n    .pipe(gulp.dest(\"public\"));\n  });\n}\n````\n\n## FAQ\n\n### How do I insert tasks? Gulp claims \"Task 'default' is not in your gulpfile\" all the time!\n\nPlease call the resolve() method after all of your module and task declarations.\n\n### gulp-di does not find my module!\n\nIn order to make your gulp plugins available, gulp-di uses\n[gulp-load-plugins](https://www.npmjs.com/package/gulp-load-plugins) internally\nby default.\n\nThe default pattern is ['gulp-*', 'gulp.*', '!gulp-di']. You need to initialize\ngulp-di using the \"options\" object in order to make plugins with arbitrary names\navailable:\n\n````js\nconst gulp = require('gulp');\nlet di = require('gulp-di')(gulp, {\n  pattern : ['gulp-*', 'gulp.*', '!gulp-di', 'webpack-stream']\n});\n\ndi.task((webpackStream) =\u003e {\n  gulp.task('webpack', () =\u003e {\n    return gulp.src('src/client.js')\n    .pipe(webpackStream({ output : { filename : '[name].js' }}))\n    .pipe(gulp.dest('public'));\n  });\n});\n\ndi.resolve();\n\n````\n\n### Is it possible to add tasks asynchronously?\n\nNo, you will need to set up asynchronous tasks which depend on each other in\norder to perform asynchronous tasks. Nevertheless, all tasks must be declared\nsynchronously in order to use Gulp correctly.\n\n### I dislike the camelCaseName of my favorite module, can I change it?\n\nUsing [gulp-load-plugins](https://www.npmjs.com/package/gulp-load-plugins), you\ncan change the assigned name for arbitrary modules.\n\n#### Using a ``rename`` object:\n\n````js\nlet di = require('gulp-di')(gulp, {\n  rename : {\n    webpackStream : 'webpack'\n  }\n});\n````\n\n#### Using a ``renameFn``:\n````js\nlet replacements = { webpackStream : 'webpack'};\nlet di = require('gulp-di')(gulp, {\n  renameFn : (key) =\u003e return replacements[key]\n});\n````\n\n## License\n\nMIT\n","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcmtt%2Fgulp-di","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcmtt%2Fgulp-di","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcmtt%2Fgulp-di/lists"}