Giter VIP home page Giter VIP logo

gulp-inject's Introduction

gulp-inject


HELP WANTED

Contributors are welcomed!

I don't have enough time to maintain this plugin as I would want to, so I'm looking for people who want to help out and be contributors/repository admins.

Interested?

Contact me! See package.json for contact information.


NPM version semantic-release Build Status XO code style Dependency Status

A stylesheet, javascript and webcomponent reference injection plugin for gulp. No more manual editing of your index.html!

Contents

Introduction

gulp-inject takes a stream of source files, transforms each file to a string and injects each transformed string into placeholders in the target stream files. See Basic usage and More examples below.

Default transforms and placeholders exists for injecting files into html, jade, pug, jsx , less, slm, haml and sass / scss files.

Installation

Install gulp-inject as a development dependency:

npm install --save-dev gulp-inject

Basic usage

The target file src/index.html:

Each pair of comments are the injection placeholders (aka. tags, see options.starttag and options.endtag).

<!DOCTYPE html>
<html>
<head>
  <title>My index</title>
  <!-- inject:css -->
  <!-- endinject -->
</head>
<body>

  <!-- inject:js -->
  <!-- endinject -->
</body>
</html>

The gulpfile.js:

var gulp = require('gulp');
var inject = require('gulp-inject');

gulp.task('index', function () {
  var target = gulp.src('./src/index.html');
  // It's not necessary to read the files (will speed up things), we're only after their paths:
  var sources = gulp.src(['./src/**/*.js', './src/**/*.css'], {read: false});

  return target.pipe(inject(sources))
    .pipe(gulp.dest('./src'));
});

src/index.html after running gulp index:

<!DOCTYPE html>
<html>
<head>
  <title>My index</title>
  <!-- inject:css -->
  <link rel="stylesheet" href="/src/style1.css">
  <link rel="stylesheet" href="/src/style2.css">
  <!-- endinject -->
</head>
<body>

  <!-- inject:js -->
  <script src="/src/lib1.js"></script>
  <script src="/src/lib2.js"></script>
  <!-- endinject -->
</body>
</html>

More examples

Injecting files relative to target files

By default the injected file paths are relative to each source file's cwd (see options.ignorePath). If options.relative is set to true each injected path will be relative to each target file's directory instead.

Project structure:

└── src
    ├── module
    │   ├── module.js
    │   └── module.html
    └── app
        ├── main.js
        └── index.html

src/app/index.html:

<!DOCTYPE html>
<html>
<head>
  <title>My Index</title>
</head>
<body>
  <h1>Home</h1>
  <!-- inject:js -->
  <!-- endinject -->
</body>
</html>

src/module/module.html:

<!DOCTYPE html>
<html>
<head>
  <title>Module</title>
</head>
<body>
  <h1>Module</h1>
  <!-- inject:js -->
  <!-- endinject -->
</body>
</html>

gulpfile.js:

var inject = require('gulp-inject');

gulp.src('./src/**/*.html')
  .pipe(inject(gulp.src('./src/**/*.js', {read: false}), {relative: true}))
  .pipe(gulp.dest('./src'));

Resulting src/app/index.html:

<!DOCTYPE html>
<html>
<head>
  <title>My Index</title>
</head>
<body>
  <h1>Home</h1>
  <!-- inject:js -->
  <script src="main.js"></script>
  <script src="../module/module.js"></script>
  <!-- endinject -->
</body>
</html>

Resulting src/module/module.html:

<!DOCTYPE html>
<html>
<head>
  <title>Module</title>
</head>
<body>
  <h1>Home</h1>
  <!-- inject:js -->
  <script src="../app/main.js"></script>
  <script src="module.js"></script>
  <!-- endinject -->
</body>
</html>

Injecting files from multiple source streams

This example demonstrates how to inject files from multiple different streams into the same injection placeholder.

Install event-stream with: npm install --save-dev event-stream and use its merge function.

Code:

var es = require('event-stream'),
    inject = require('gulp-inject'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify');

// Concatenate vendor scripts
var vendorStream = gulp.src(['./src/vendors/*.js'])
  .pipe(concat('vendors.js'))
  .pipe(gulp.dest('./dist'));

// Concatenate AND minify app sources
var appStream = gulp.src(['./src/app/*.js'])
  .pipe(concat('app.js'))
  .pipe(uglify())
  .pipe(gulp.dest('./dist'));

gulp.src('./src/index.html')
  .pipe(inject(es.merge(vendorStream, appStream)))
  .pipe(gulp.dest('./dist'));

Multiple sources when order is important

Use stream-series.

Code:

var series = require('stream-series'),
    inject = require('gulp-inject');

var vendorStream = gulp.src(['./src/vendors/*.js'], {read: false});

var appStream = gulp.src(['./src/app/*.js'], {read: false});

gulp.src('./src/index.html')
  .pipe(inject(series(vendorStream, appStream))) // This will always inject vendor files before app files
  .pipe(gulp.dest('./dist'));

Injecting some files into <head> and some into <body>

Method 1: Use gulp-inject's starttag option.

gulpfile.js:

var inject = require('gulp-inject');

gulp.src('./src/index.html')
  .pipe(inject(gulp.src('./src/importantFile.js', {read: false}), {starttag: '<!-- inject:head:{{ext}} -->'}))
  .pipe(inject(gulp.src(['./src/*.js', '!./src/importantFile.js'], {read: false})))
  .pipe(gulp.dest('./dist'));

And in your ./src/index.html:

<!DOCTYPE html>
<html>
<head>
  <title>My index</title>
  <!-- inject:head:js -->
  <!-- only importantFile.js will be injected here -->
  <!-- endinject -->
</head>
<body>

  <!-- inject:js -->
  <!-- the rest of the *.js files will be injected here -->
  <!-- endinject -->
</body>
</html>

Method 2: Use gulp-inject's name option.

gulpfile.js:

var inject = require('gulp-inject');

gulp.src('./src/index.html')
  .pipe(inject(gulp.src('./src/importantFile.js', {read: false}), {name: 'head'}))
  .pipe(inject(gulp.src(['./src/*.js', '!./src/importantFile.js'], {read: false})))
  .pipe(gulp.dest('./dist'));

And in your ./src/index.html:

<!DOCTYPE html>
<html>
<head>
  <title>My index</title>
  <!-- head:js -->
  <!-- only importantFile.js will be injected here -->
  <!-- endinject -->
</head>
<body>

  <!-- inject:js -->
  <!-- the rest of the *.js files will be injected here -->
  <!-- endinject -->
</body>
</html>

Injecting all files for development

If you use Bower for frontend dependencies I recommend using main-bower-files and injecting them as well.

gulpfile.js:

var bowerFiles = require('main-bower-files'),
    inject = require('gulp-inject'),
    stylus = require('gulp-stylus'),
    es = require('event-stream');

var cssFiles = gulp.src('./src/**/*.styl')
  .pipe(stylus())
  .pipe(gulp.dest('./build'));

gulp.src('./src/index.html')
  .pipe(inject(gulp.src(bowerFiles(), {read: false}), {name: 'bower'}))
  .pipe(inject(es.merge(
    cssFiles,
    gulp.src('./src/app/**/*.js', {read: false})
  )))
  .pipe(gulp.dest('./build'));

src/index.html:

<!DOCTYPE html>
<html>
<head>
  <title>My index</title>
  <!-- bower:css -->
  <!-- bower installed css files will go here... -->
  <!-- endinject -->
  <!-- inject:css -->
  <!-- built css files will go here... -->
  <!-- endinject -->
</head>
<body>

  <!-- bower:js -->
  <!-- bower installed scripts will go here... -->
  <!-- endinject -->
  <!-- inject:js -->
  <!-- app scripts will go here... -->
  <!-- endinject -->
</body>
</html>

Note remember to mount ./bower_components, ./build and ./src/app as static resources in your server to make this work.

Injecting AngularJS scripts for development

If you're writing an AngularJS application and follow Google's Angular APP Structure Recommendations, which I think you should, it's important that the script files are injected in the correct order to avoid module instantiation problems like Uncaught Error: [$injector:modulerr].

To do this you can use gulp-angular-filesort together with gulp-inject like so:

var angularFilesort = require('gulp-angular-filesort'),
    inject = require('gulp-inject');

gulp.src('./src/index.html')
  .pipe(inject(
    gulp.src('./src/app/**/*.js') // gulp-angular-filesort depends on file contents, so don't use {read: false} here
      .pipe(angularFilesort())
    ))
  .pipe(gulp.dest('./build'));

Injecting into a json-file

You can customize gulp-inject further by using the transform function option, e.g. by injecting files into a json-file.

Code:

gulp.src('./files.json')
  .pipe(inject(gulp.src(['./src/*.js', './src/*.css', './src/*.html'], {read: false}), {
    starttag: '"{{ext}}": [',
    endtag: ']',
    transform: function (filepath, file, i, length) {
      return '  "' + filepath + '"' + (i + 1 < length ? ',' : '');
    }
  }))
  .pipe(gulp.dest('./'));

Initial contents of files.json:

{
  "js": [
  ],
  "css": [
  ],
  "html": [
  ]
}

Injecting with custom transform function with default fallback

The default transform function is available to use e.g. as a default fallback.

Used here to inject Word documents as <a> tags below:

index.html:

<!DOCTYPE html>
<html>
<head>
  <title>My documents</title>
</head>
<body>
  <h1>Documents</h1>
  <ul>
    <!-- inject:docx -->
    <!-- endinject -->
  </ul>
  <!-- inject:js -->
  <!-- endinject -->
</body>
</html>

gulpfile.js:

var inject = require('gulp-inject');

gulp.src('./index.html')
  .pipe(inject(
    gulp.src(['./*.js', './docs/*.docx'], {read: false}), {
      transform: function (filepath) {
        if (filepath.slice(-5) === '.docx') {
          return '<li><a href="' + filepath + '">' + filepath + '</a></li>';
        }
        // Use the default transform as fallback:
        return inject.transform.apply(inject.transform, arguments);
      }
    }
  ))
  .pipe(gulp.dest('./'));

Resulting index.html:

<!DOCTYPE html>
<html>
<head>
  <title>My documents</title>
</head>
<body>
  <h1>Documents</h1>
  <ul>
    <!-- inject:docx -->
    <li><a href="/docs/document1.docx"></a></li>
    <li><a href="/docs/document2.docx"></a></li>
    <!-- endinject -->
  </ul>
  <!-- inject:js -->
  <script src="/lib1.js"></script>
  <script src="/lib2.js"></script>
  <!-- endinject -->
</body>
</html>

Injecting dist files into bower.json's main section

Code:

gulp.src('./bower.json')
  .pipe(inject(gulp.src(['./dist/app.min.js', './dist/app.min.css'], {read: false}), {
    starttag: '"main": [',
    endtag: ']',
    transform: function (filepath, file, i, length) {
      return '  "' + filepath + '"' + (i + 1 < length ? ',' : '');
    }
  }))
  .pipe(gulp.dest('./'));

Injecting all javascript files into a karma config file

Code:

gulp.src('./karma.conf.js')
  .pipe(inject(gulp.src(['./src/**/*.js'], {read: false}), {
    starttag: 'files: [',
    endtag: ']',
    transform: function (filepath, file, i, length) {
      return '  "' + filepath + '"' + (i + 1 < length ? ',' : '');
    }
  }))
  .pipe(gulp.dest('./'));

Injecting files contents

In order to inject files contents you have to provide custom transform function, that will return file contents as string. You also have to omit {read: false} option of gulp.src in this case. Example below shows how to inject contents of html partials into head of index.html:

Code:

gulp.src('./src/index.html')
  .pipe(inject(gulp.src(['./src/partials/head/*.html']), {
    starttag: '<!-- inject:head:{{ext}} -->',
    transform: function (filePath, file) {
      // return file contents as string
      return file.contents.toString('utf8')
    }
  }))
  .pipe(gulp.dest('./dest'));

And in your ./src/index.html:

<!DOCTYPE html>
<html>
<head>
  <title>My index</title>
  <!-- inject:head:html -->
  <!-- contents of html partials will be injected here -->
  <!-- endinject -->
</head>
<body>
</body>
</html>

Injecting files contents based on file path

In order to inject files based on file path you have to provide custom starttag which includes {{path}}. Additionally, in order to inject file contents include transform function, that will return file contents as string. You also have to omit {read: false} option of gulp.src in this case. Path can be either absolute, or relative in which case you should set [options.relative] to true. Example below shows how to inject contents of html partials into index.html:

Code:

gulp.src('./src/index.html')
  .pipe(inject(gulp.src(['./src/partials/head/*.html']), {
    starttag: '<!-- inject:{{path}} -->',
    relative: true,
    transform: function (filePath, file) {
      // return file contents as string
      return file.contents.toString('utf8')
    }
  }))
  .pipe(gulp.dest('./dest'));

And in your ./src/index.html:

<!DOCTYPE html>
<html>
<head>
  <title>My index</title>
  <!-- inject:path/to/your/file.ext -->
  <!-- contents of html partials will be injected here -->
  <!-- endinject -->
</head>
<body>
</body>
</html>

API

inject(sources, options)

Parameter: sources
Type: Stream

Provide a Vinyl File Stream as input to inject, see examples above.

Parameter: options
Type: Object

For available options see Options

Options

options.ignorePath

Type: String or Array

Default: NULL

A path or paths that should be removed from each injected file path.

This could also be solved by setting the cwd option for your gulp.src streams, each source file's cwd is automatically removed from its path before injection (if not options.relative is set to true, see below).

options.relative

Type: Boolean

Default: false

If set to true paths for the injected files will be relative to each target file, this also means that each source file's cwd is not necessary to remove from its path.

options.addPrefix

Type: String

Default: NULL

A path that should be prefixed to each injected file path.

options.addSuffix

Type: String

Default: NULL

A path that should be suffixed to each injected file path.

options.addRootSlash

Type: Boolean

Default: !options.relative

The root slash is automatically added at the beginning of the path ('/'), or removed if set to false.

options.name

Type: String

Default: "inject"

Used in the default start and end tags below.

options.removeTags

Type: Boolean

Default: false

When true the start and end tags will be removed when injecting files.

options.empty

Type: Boolean

Default: false

When true all tags without corresponding files will be emptied.

Warning this has the potential issue of emptying more than expected.

options.starttag

Type: String|Function(targetExt, sourceExt)

Params (if function):

  • targetExt - The file extension of the target file
  • sourceExt - The file extension of source file

Purpose:

Used to dynamically set starting placeholder tag depending on file extensions. In the provided string, or the string returned from the given function, the string {{ext}} is replaced with the source file extension name, e.g. "css", "js" or "html". {{name}} will be replaced by options.name. {{path}} will be replaced by path to source file (when used together with [options.relative] it will allow relative path to source file.

Default:

A function dependent on target file type and source file type that returns:

  • html as target: <!-- {{name}}:{{ext}} -->
  • haml as target: -# {{name}}:{{ext}}
  • jade as target: //- {{name}}:{{ext}}
  • pug as target: //- {{name}}:{{ext}}
  • jsx as target: {/* {{name}}:{{ext}} */}
  • slm as target: / {{name}}:{{ext}}
  • less as target: /* {{name}}:{{ext}} */
  • sass, scss as target: /* {{name}}:{{ext}} */

options.endtag

Type: String|Function(targetExt, sourceExt)

Params (if function):

  • targetExt - The file extension of the target file
  • sourceExt - The file extension of source file

Purpose:

Used to dynamically set ending placeholder tag depending on file extensions. In the provided string, or the string returned from the given function, the string {{ext}} is replaced with the source file extension name, e.g. "css", "js" or "html". {{name}} will be replaced by options.name. {{path}} will be replaced by path to source file.

Default:

A function dependent on target file type and source file type that returns:

  • html as target: <!-- endinject -->
  • haml as target: -# endinject
  • jade as target: //- endinject
  • pug as target: //- endinject
  • jsx as target: {/* endinject */}
  • slm as target: / endinject
  • less as target: /* endinject */
  • sass, scss as target: /* endinject */

options.transform

Type: Function(filepath, file, index, length, targetFile)

Params:

  • filepath - The "unixified" path to the file with any ignorePath's removed, addPrefix and addSuffix added
  • file - The File object to inject given from gulp.src
  • index - 0-based file index
  • length - Total number of files to inject for the current file extension
  • targetFile - The target file to inject into

Purpose:

Used to generate the content to inject for each file.

Default:

A function dependent on target file type and source file type that returns:

Injecting into html

  • css files: <link rel="stylesheet" href="<filename>.css">
  • js files: <script src="<filename>.js"></script>
  • coffee files: <script type="text/coffeescript" src="<filename>.coffee"></script>
  • html files: <link rel="import" href="<filename>.html">
  • png files: <img src="<filename>.png">
  • gif files: <img src="<filename>.gif">
  • jpg files: <img src="<filename>.jpg">
  • jpeg files: <img src="<filename>.jpeg">

If options.selfClosingTag is true the default transformer above will make the <link> and <img> tags self close, i.e: <link ... /> and <img ... /> respectively.

Injecting into jsx

The same as for injecting into html above with options.selfClosingTag set to true.

Injecting into jade

  • css files: link(rel="stylesheet", href="<filename>.css")
  • js files: script(src="<filename>.js")
  • coffee files: script(type="text/coffeescript", src="<filename>.coffee")
  • html files: link(rel="import", href="<filename>.html")
  • png files: img(src="<filename>.png")
  • gif files: img(src="<filename>.gif")
  • jpg files: img(src="<filename>.jpg")
  • jpeg files: img(src="<filename>.jpeg")

Injecting into pug

  • css files: link(rel="stylesheet", href="<filename>.css")
  • js files: script(src="<filename>.js")
  • coffee files: script(type="text/coffeescript", src="<filename>.coffee")
  • html files: link(rel="import", href="<filename>.html")
  • png files: img(src="<filename>.png")
  • gif files: img(src="<filename>.gif")
  • jpg files: img(src="<filename>.jpg")
  • jpeg files: img(src="<filename>.jpeg")

Injecting into slm

  • css files: link rel="stylesheet" href="<filename>.css"
  • js files: script src="<filename>.js"
  • coffee files: script type="text/coffeescript" src="<filename>.coffee"
  • html files: link rel="import" href="<filename>.html"
  • png files: img src="<filename>.png"
  • gif files: img src="<filename>.gif"
  • jpg files: img src="<filename>.jpg"
  • jpeg files: img src="<filename>.jpeg"

Injecting into haml

  • css files: %link{rel:"stylesheet", href:"<filename>.css"}
  • js files: %script{src:"<filename>.js"}
  • coffee files: %script{type:"text/coffeescript", src:"<filename>.coffee"}
  • html files: %link{rel:"import", href:"<filename>.html"}
  • png files: %img{src:"<filename>.png"}
  • gif files: %img{src:"<filename>.gif"}
  • jpg files: %img{src:"<filename>.jpg"}
  • jpeg files: %img{src:"<filename>.jpeg"}

Injecting into less

  • css files: @import "<filename>.css";
  • less files: @import "<filename>.less";

Injecting into scss

  • css files: @import "<filename>.css";
  • scss files: @import "<filename>.scss";
  • sass files: @import "<filename>.sass";

Injecting into sass

  • css files: @import "<filename>.css"
  • sass files: @import "<filename>.sass"
  • scss files: @import "<filename>.scss"

options.selfClosingTag

Type: Boolean

Default: false

Affects the default options.transform function, see above.

options.quiet

Type: Boolean

Default: false

Lower the verbosity by setting this to true, suppressing the logging of successful injections.

options.templateString

DEPRECATED!

Deprecated since v.1.0. Use gulp-file instead:

var gulp = require('gulp');
var file = require('gulp-file');
var inject = require('gulp-inject');

file('index.html', '<html><head></head></html>')
  .pipe(inject(gulp.src(['./src/app/**/*.js']), {
    starttag: '<head>',
    endtag: '</head>'
  }))
  .pipe(gulp.dest('./dest'));

options.sort

DEPRECATED!

Deprecated since v.1.0. Use sort-stream instead:

var gulp = require('gulp');
var sort = require('sort-stream');
var inject = require('gulp-inject');

gulp.src('index.html')
  .pipe(inject(
    gulp.src(['./src/app/**/*.js'])
      .pipe(sort(function (a, b) {
      // Sort condition here...
      }))
  ))
  .pipe(gulp.dest('./dest'));

inject.transform

The default transform function is exposed in the public API.

For more details see the code with tests.

inject.transform.html

The default transform function for files into html, or other file types not jade, pug, jsx, slm, less, scss, sass or haml.

inject.transform.jade

The default transform function for files into jade.

inject.transform.pug

The default transform function for files into pug.

inject.transform.jsx

The default transform function for files into jsx.

inject.transform.slm

The default transform function for files into slm.

inject.transform.haml

The default transform function for files into haml.

inject.transform.less

The default transform function for files into less.

inject.transform.sass

The default transform function for files into sass.

inject.transform.scss

The default transform function for files into scss.

License

MIT © Joakim Carlstein

gulp-inject's People

Contributors

adam-beck avatar akreitals avatar callmenick avatar corintho avatar creade avatar crfroehlich avatar deepan83 avatar dependabot[bot] avatar gligoran avatar harryburns avatar jeroenheijmans avatar joakimbeng avatar josephpage avatar koblass avatar kroid avatar lukehorvat avatar marcotaubmann avatar meeroslav avatar minipai avatar overzealous avatar pgilad avatar quicksnap avatar rejas avatar robbiet480 avatar schlueter avatar slhenty avatar superbrothers avatar totakoko avatar w0rm avatar wilsonjackson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gulp-inject's Issues

Can't remove beginning of injected path using 'IgnorePath'

I'm trying to have gulp-inject, inject a bunch of JS files in my app.

My folder structure looks like this

gulpfile.js
app/
    scripts/
    index.html

The file comments that get injected look like this.
<script src="/app/scripts/app.js"></script>

However I need to remove the /app/ so the index.html file loads the .js files properly.
I've tried adding this {ignorePath: 'app'} but it doesn't seem to remove it from the inject comments.

Any ideas?

Nothing seems to happen...

Hi, thanks for this plugin, it's exactly what I was looking for. I have a problem though, it's not working for me :(

Here's my gulpfile:

var gulp = require('gulp');
var inject = require('gulp-inject');

// dynamically inject app assets to the HTML
gulp.task('build', function () {
  return gulp.src(['./src/app/**/*.js', './src/app/**/*.css'], { read: false })
    .pipe(inject('./src/index.html'))
    .pipe(gulp.dest('./dist'));
});

gulp.task('default',function () {
  gulp.run('build');
});

But when I run gulp, I don't get any dist directory. If I create it manually, after running gulp the directory remains empty.

I'm new to gulp, so... am I missing something here?

Thank you!

Is File.base being set incorrectly?

No matter what I do, when I use this plugin, it overwrites the original file.

I'm using this code:

return gulp.src(['.build/**/*.*', '!./build/index.html'], {read:false})
        .pipe(inject('src/index.html'))
        .pipe(gulp.dest('./build'));

I would expect the file to be output as './build/index.html', but it is definitely overwriting the source.

I think the issue might be that base is being set as the basename of the file (ie: index.html), rather than the base path (ie: src/). When you simply call gulp.src() on the file, that's what gulp sets it to:

Output of gulp.src('src/index.html').debug()

File
cwd:      ~/myApp
base:     ~/myApp/src/
path:     ~/myApp/src/index.html
stat:     [object Object]
contents: <!DOCTYPE html>
<html ng-app="djpack" ng...

Output of gulp.src([...]).pipe(inject('src/index.html')).debug()

File
cwd:      ~/myApp
base:     index.html
path:     ~/myApp/src/index.html
contents: <!DOCTYPE html>
<html ng-app="djpack" ng...

Anyway, I think this is broken. base is used by gulp.dest() to determine the correct subfolders to save under.

As a suggestion, would it be possible to instead take a pipe as the source for the injected file? ie:

gulp.src([...]).pipe(inject(gulp.src('src/index.html'))).dest(...');

Feature:add namespacing to inject scripts

If I have 2 script groups in my html file, such as scripts and vendors, I would want to inject different files to different inject scripts holders. This would require that I can add namespacing to the inject target scripts (or html/css). Such as:

<!-- inject:js (vendors) -->
<!-- endinject -->

<!-- inject:js (scripts) -->
<!-- endinject -->

And then when piping the src stream I could namespace my injects:

var inject = require("gulp-inject");

gulp.src('./src/index.html')
    .pipe(inject(gulp.src(["./src/*.js"], {read: false}), {namespace:'scripts'}))
    .pipe(inject(gulp.src(["./src/vendors/*.js"], {read:false}), {namespace:'vendors'}))
    .pipe(gulp.dest("./dist"));

This will allow for separate uglify & concat tasks based on namespacing. I for example want to uglify & concat scripts but only concat vendor scripts.

Transform ignored

I got this task

gulp.task('dev-admin-index',function(){
    var target = gulp.src('target');

    var sources = gulp.src([
        'public/js/controller/*.js',
    ],{
        read:false
    },{
        transform: function (filepath) {
            return 'hello-world';
        }
    });

    return target
        .pipe(inject(sources))
        .pipe(gulp.dest('views/admin'));
});

no matter what I return on transform function on target file the file will be "public/js/controller/file.js"

working with multi level file structure

I got a problem with paths to injected files, my app structure looks like below

gulpfile.js
doc/
   build/
   src/
        components/
            grid.html
            forms.html
        styles/
            base.css
   index.html

I want to inject css file to every html file with keeping properly path, but it only works with index.html. How can I keep properly path in each level?

what i have:

index.html

<link rel="stylesheet" href="styles/css/base.css">

grid.html

<link rel="stylesheet" href="styles/css/base.css">

etc.

what i need:

index.html

<link rel="stylesheet" href="styles/css/base.css>

grid.html

<link rel="stylesheet" href="../styles/css/base.css">

etc

my gulpfile.js

var paths = {
    html: './doc/src/**/*.html',
    styles: './doc/build/styles/css/*.css',
    out: './doc/build'
};

gulp.task('inject', function () {
    gulp.src(paths.html)
        .pipe(inject(gulp.src([paths.styles], {read: false}), {
                ignorePath: 'doc/build',
                addRootSlash: false
            }
        ))
        .pipe(gulp.dest(paths.out));
});

Cannot inject into specific `starttag`

Using these comments:

<!-- inject:vendors:js -->
<!-- endinject -->

<!-- inject:vendors:css -->
<!-- endinject -->

And these options on gulp-inject:

{ relative: true, 
  addRootSlash: false, 
  starttag: '<!-- inject:vendors:{{ext}} -->'
}

Nothing gets injected in either comment blocks

If I change the comment block to:

<!-- inject:js -->
<!-- endinject -->

<!-- inject:css -->
<!-- endinject -->

The tags are injected, EVEN if I leave the starttag option to '<!-- inject:vendors:{{ext}} -->'

I also tried using camel-cased option name startTag to no avail


For clarification, here's how I call the plugin:

return sourceStreams.phoenixIndex()
    .pipe(g.inject(sourceStreams.build.vendorsScripts()), options.injections.vendors);

sourceStreams.phoenixIndex() and sourceStreams.build.vendorsScripts(): A lazypipe that returns a stream of files (the 1st one being the index.html, the second one being the list of bower-dependencies)
options.injections.vendors: this object:

{ relative: true, 
  addRootSlash: false, 
  starttag: '<!-- inject:vendors:{{ext}} -->'
}

Unable to inject js and css !

Hi,

I tired this but its not working.

  gulp.src('src/*.html')
   .pipe($.inject(gulp.src('dist/assets/js/*.js')), {
      read: false,
      starttag: '<!-- inject:partials -->',
      addRootSlash: false,
      addPrefix: '../'
   }))'

.pipe($.inject(gulp.src('dist/assets/css/*.css'),{
   read:false,
   starttag: '<!-- inject:css -->'
 }))`

I am unable to see these tags into my index.html

Possible to have multiple injects?

I need to inject my files in a specific order. I was wondering if I could create multiple comment blocks and have different files injected into them. Example: etc

Similar to the inject head example.

base path

Hi. I'm using this with connect in development. Right now what I'm doing is copying my entire app to ./build. I then run gulp-inject on ./build/index.html and start a connect start server on ./build. The problem I'm getting now is that all the injected scripts are prefixed with /build/. Am I just missing something or just going about it the wrong way or is this something that would be better fixed internally to gulp-inject?

inject fires before files are added to /dist

I'm using gulp-inject and the first time i fire gulp it doesn't add the injects in the html, only the second time or if watch fires.

This is because I think it takes time to write the files in /dist, which is the folder I use to inject files

    .pipe(inject(
        gulp.src([dest + 'js/**/*.js', dest + 'css/**/*.css'], {read: false}),
        {ignorePath: 'public', addRootSlash: false}
    ))

This is not a big problem but it is a big problem when using git-rev or other revision modules where you have to inject the last files generated.

Also, is there an options to ignore files with have a .min? Usually in the /css and /js folder i have normal files and .min files

Injecting Bower components does not respect the dependencies order

First of all, congrats for the awesome plugin.

I'm using it in my gulpfile to inject Bower components but it seems it does not recognize the correct order of dependencie's order, causing issues with the bower components not working properly.

Is there a way to let it work like "wiredep" and let it understand in what order to inject dependencies' references?

Thanks in advance.

Not working with gulp.watch / gulp-watch

I've tried using gulp.watch and the gulp-watch plugin, but anytime a change is detected, my index.html file does not inject the <!-- inject:js --> and <!-- inject:css --> tags. index.html is inject correctly when I first run my gulp task, but when I change index.html, it doesn't re-inject.

Using gulp.watch

gulp.task('copy', function() {
    gulp.src('./public/index.html')
        .pipe($.inject(vendorStream, {
            ignorePath: '/dist/',
            addRootSlash: false
        }))
        .pipe(gulp.dest('./dist'))
        .pipe(connect.reload());
});


gulp.task('watch', function() {
    gulp.watch([paths.html], ['copy']);
    ...
});

Using gulp-watch

gulp.task('copy', function() {
    gulp.src('./public/index.html')
        .pipe($.watch(function(files) {
            files.pipe($.inject(vendorStream, {
                ignorePath: '/dist/',
                addRootSlash: false
            }))
            .pipe(gulp.dest('./dist'))
            .pipe(connect.reload());
        }));
});

gulp-inject running very slow

I'm using the gulp-angular yeoman generator which uses gulp-inject in the build task (actually, the html task) like this:

gulp.src('app/*.html')
.pipe($.inject(gulp.src('.tmp/partials/**/*.js'), {
      read: false,
      starttag: '<!-- inject:partials -->',
      addRootSlash: false,
      addPrefix: '../'
    }))

There are just 2 html files with inject templates and only one js file and it takes more than 7 seconds to execute this part of the task. Any hints?

Take a Vinyl File Stream as input parameter to plugin

(see discussion in #8 )
Improving gulpyness
To make gulp-inject more "gulpy" it should take a Vinyl File Stream as a parameter, instead of path to template.

If a Vinyl File Stream is given as parameter gulp-inject will assume it contains the files to inject, and not the files to inject into.

Usage example

gulp.src('./src/index.html')
  .pipe(inject(gulp.src(['./src/*.js', './src/*.css'])))
  .pipe(gulp.dest('./build'));

Backwards compatibility
If a string or object is given as first parameter to gulp-inject, it will use the old behavior.

Unable to addPrefix a protocol relevant URL

If I try to addPrefix //myassets.s3.amazonaws.com, I get /myassets.s3.amazonaws.com/myJS.js. If I set addRootSlash to false, I get myassets.s3.amazonaws.com/myJS.js. If I set addPrefix to http://myassets.s3.amazonaws.com"it outputs correctly. I'm guessing it's one of the regexes that's clobbering the URL, but can't identify which one specifically.

Injects a thousand empty strings

var bower = require('main-bower-files');
var inject  = require('gulp-inject');

gulp.task('test', function(){
  return gulp.src('app/index.html')
             .pipe(inject(gulp.src(bower()), {starttag: '<!-- inject:bower -->'}))
             .pipe(gulp.dest('app'));
});

results in a few thousand new lines in my app/index.html inject tag. I've debugged the output for bower() and sure enough it grabs all the bower files. Thoughts?

Using gulp-inject to inject file contents into html

Hello!

I need to inject svg sprite combined with gulp-svgstore into html. It didn't work out of box, so I had to define custom transform function:

transform: function (filePath, file) { return file.contents.toString('utf8') }

Is this a correct way of using gulp-inject? Has it been designed with this usage in mind?

Last inject override.

Getting issue #39 if I inject from two different gulp tasks. The same task it does not override. But separate tasks it causes the most recent task with inject to override the inject of a previous task.

Script Tags are generated in a random order each time

When using this plugin with the following config:

return gulp.src("index.html")
    .pipe(g.inject(gulp.src(["scripts/**/*.js",
                             "!scripts/**/*.test.js"],
                   {read: false}), {relative: true}))
    .pipe(gulp.dest("dist"));

I get a different order of files each time I run it, even if the filesystem hasn't changed, which makes it hard to use the gulp-rev plugin efficiently, because you get a different hash each time.

Is there a way to keep the recursive file search consistent?

Thanks!

Option to remove inject comments

Suggested enhancement: an option to remove the inject / endinject comment pair after injection of the source tags. The endinject comment could be optional if this option is set.

Inject a CDN URL

It is not immediately clear how one would inject a url for a CDN?

E.g. how might one inject the following:

["http://cdnjs.cloudflare.com/ajax/libs/jasmine/1.3.1/jasmine.js", "./spec/test"]

It would appear that gulp.src() ignores the URL, and I did not see any unit tests corresponding with this functionality.

Many thanks for any thoughts. Cheers.

trouble injecting bower dependencies

I have a simple app structure:

bower_components/
scripts/
index.html
bower.json
gulpfile.js

I'd have these in index.html:

<!-- bower:css -->
  <!-- endinject -->
<!-- bower:js -->
  <!-- endinject -->

and my gulpfile.js looks like so:

var gulp = require('gulp'),
    bowerFiles = require('main-bower-files'),
    inject = require("gulp-inject");

gulp.task('index', function(){
  gulp.src('./index.html')
    .pipe(inject(gulp.src(bowerFiles(), { read: false }, { name: 'bower' })))

})

When I run $ gulp index it looks successful but the files don't inject

[gulp] Using gulpfile ~/Projects/ng-morris/gulpfile.js
[gulp] Starting 'index'...
[gulp] Finished 'index' after 21 ms
[11:25:18] gulp-inject 6 files into index.html.

addRootSlash not working with cwd?

I'm trying to drop the rootSlash from the output (needed to run on mobile devices).

Tried:

var src = {
  cwd: 'app',
  scripts: '{,modules/*/}scripts/**/*.js'
};

// [...]

.pipe(inject(gulp.src(src.scripts, {cwd: src.cwd, base: src.cwd}, {addRootSlash: false}).pipe(angularFilesort())))

But I end up with a rootSlash anyway, on an index.jade file.

Tried addPrefix: '.', as a workaround, but it's not working.

option to operate on already-in-memory buffer?

I already have my templated file in memory because I've been doing other things with it. In fact, it's a clone of my original src file. Would it be possible to have an option that can operate directly on a buffer (file.contents) or a string (file.contents.toString('utf8'))?

I would otherwise need to save my file in a temporary location in order to get gulp-inject to do its work (something that feels pretty un-gulpy).

Completely strip path from file.

What if I have a very large project where at build time all of my javascript files are moved into a build folder /build/js.

Each of their paths may be dramatically different and using ignorePath would get out of hand.

Is there a way to completely remove the path from every file so I can specify my own like:

options:{
  ignorePath:['*'],
  addPrefix:'/js/'
}

Cannot inject JS into body

I cannot seem to inject js into the body. It only works if I inject into the head, even when using starttag instead of defaults.

Does app work without adding an endtag?

Unless injecting into a non-html file (i.e the JSON example) I don't see any need to specify <!-- endinject --> in the html file.

So this pattern:

<!-- inject:js -->
<!-- any *.js files among your sources will go here as: <script src="FILE"></script> -->
<!-- endinject -->

Is the same as this one:

<!-- inject:js -->

But just shorter, more concise and less messy. The endtags IMO are a remnant of the usemin patterns where you actually specify all files beforehand unlike gulp-inject where files just come from a stream.

What do you think?

gulp-inject silently fails on gulp-watch streams

I haven't figured out why, but if you attempt to gulp-inject a stream which is wrapped by gulp-watch (not gulp.watch) the stream files disappear after the inject:

var watch = require('gulp-watch'),
      inject = require('gulp-inject'),
      sass = require('gulp-sass');

css = gulp.src(path.sass)
  .pipe(watch(function(files) {
    return files
      .pipe(sass())
      .pipe(gulp.dest(path.build));
  }));

gulp.src('index.html')
  .pipe(inject(css));

Adding a .pipe(print()) with gulp-print after the .pipe(inject(css)) results in no files in the stream. So attempting to gulp.dest the file does nothing (since the stream is empty). This is a silent failure, there are no errors.

Why specify path to HTML file?

I hate to ask questions in an issue, but here goes. It seems "un-gulpy" to pass in a file path and to use fs to read that file. Isn't the gulp way to read it from the passed in stream? Is there a reason for this?

Sugestion

Hi, i'm using gulp-inject this works well, but i need a "gulp-reject", have you thought about that?

Doesn't remove injections when stream is empty

Hi,
I'm using gulp-inject to inject some files ./app/scripts/**/*.js into my index.html. When gulp finds files, the plugin works as expected and injects all files. But when I remove all files from the filesystem the files aren't removed in the index.html. I experimented a little bit and found out that when at least one file is in the stream the plugin correctly removes all others. When I remove the last file, the index.html remains untouched resulting in 404's.

I reduced the problem to this simple task to reproduce it:

gulp.task('inject', function () {
  var jsFiles = gulp.src(['./app/scripts/**/*.js']);

  return gulp.src('./app/index.html')
    .pipe($.inject(jsFiles, {relative: true}))
    .pipe(gulp.dest('./app'));
});

Am I doing something wrong or is this the intended behavior?

Relax regex for html comment matching to work with jade produced templates

Jade files with remove trailing whitespace enabled will produce invalid html inject comments with your current regex. If for some reason you want to inject files after compiling jade to html, you end up with this:
<!-- inject:js--> (missing the final space, breaking your regex). So you may want to make this space optional. Got it working by injecting before compiling.

Option to set the base URL path

Suggested enhancement: an option to set the base URL path (e.g. public_html/), so absolute URLs point to the correct path.

Afaict the only solution right now is to the transform option and manipulate the filepath.

Don't have default start/end tags so whitespace sensitive

It's a bit annoying using jade with gulp inject since there is no way (AFAIK) to add whitespace at the end of a comment.

// inject:css    ->     <!-- inject:css-->

Due to the missing space on the end both the start and end tag need to be specified in the inject config.

Is it worth having the defaults not whitespace sensitive?

Last inject override the other changes when chaining injections

Here is my code

gulp.task('dev', function() {
    gulp.src('./src/index.html')
      .pipe(inject(gulp.src(mainBowerFiles(), {read: true}), {name: 'bower'}))
      .pipe(inject(gulp.src('./src/app/**/*.js').pipe(angularFilesort())))
      .pipe(gulp.dest('./src'));
})

I get:

localhost:yo mozilla$ gulp dev
[13:22:14] Using gulpfile ~/Proj/yo/gulpfile.js
[13:22:14] Starting 'dev'...
[13:22:14] Finished 'dev' after 9.38 ms
[13:22:14] gulp-inject 1 files into index.html.
[13:22:14] gulp-inject 2 files into index.html.

And only the two files in src/app appear, the other ones don't. If I switch the pip, I get the same, the other way around.

Allow For Gulpfile to Not Have to Reside at Project Root

Using the project structure described below, gulp-inject injects absolute paths rather than regular paths. When the gulpfile is in the project root, the relative paths are injected.

Can the file paths be injected relative to the html file that they are being injected into?

Project Directory (only relevant paths)

minesweeper-angular
|
|- index.html
|
|- dev.html
|
|- Resources
|   |
|   |- scripts
|       |
|       |- js
|
|- Tasks
    |
    |- gulpfile.js

gulp-inject task in gulpfile.js

var gulp    = require('gulp')
var rename  = require('gulp-rename')
var inject = require('gulp-inject')

path.html = {
    dev     : '../dev.html',
    index   : '../index.html'
}

gulp.task(
    'html',
    function() {
        return gulp
        .src(path.html.index)
        .pipe(
            inject(

            // path.js.compile is an array of file paths
                gulp.src(path.js.compile, {read:false})
            )
        )
        .pipe(rename(path.html.dev))
        .pipe(gulp.dest('./'))
    }
)

gulp-inject delimiters in index.html (source)

<!-- inject:js -->
<!-- endinject -->

dev.html (outcome)

<!-- inject:js -->
<script src="/Users/walterroman/Sites/minesweeper-angular/Resources/scripts/lib/angular.min.js"></script>
<script src="/Users/walterroman/Sites/minesweeper-angular/Resources/scripts/lib/jquery.min.js"></script>
<script src="/Users/walterroman/Sites/minesweeper-angular/Resources/scripts/lib/angular-route.min.js"></script>
<script src="/Users/walterroman/Sites/minesweeper-angular/Resources/scripts/lib/angular-sanitize.js"></script>
<script src="/Users/walterroman/Sites/minesweeper-angular/Resources/scripts/lib/angular-cookies.min.js"></script>
<script src="/Users/walterroman/Sites/minesweeper-angular/Resources/scripts/lib/angularLocalStorage.js"></script>
<script src="/Users/walterroman/Sites/minesweeper-angular/Resources/scripts/lib/ng-slider.min.js"></script>
<script src="/Users/walterroman/Sites/minesweeper-angular/Resources/scripts/js/collections/tiles/collection.js"></script>
<script src="/Users/walterroman/Sites/minesweeper-angular/Resources/scripts/js/models/sliders/model.js"></script>
<script src="/Users/walterroman/Sites/minesweeper-angular/Resources/scripts/js/models/modals/model.js"></script>
<script src="/Users/walterroman/Sites/minesweeper-angular/Resources/scripts/js/models/tile/model.js"></script>
<script src="/Users/walterroman/Sites/minesweeper-angular/Resources/scripts/js/models/tile/modelMethods.js"></script>
<script src="/Users/walterroman/Sites/minesweeper-angular/Resources/scripts/js/controllers/board.js"></script>
<script src="/Users/walterroman/Sites/minesweeper-angular/Resources/scripts/js/app.js"></script>
<!-- endinject -->

Expectation
For each js file to be injected with relative paths, rather than absolute. In this specific case, without '/Users/walterroman/Sites/minesweeper-angular' prefixed onto the file path.

filepath

I have the following lines of code:

gulp.src('build/js/**/*.js', {read: false})
        .pipe(inject("app/views/includes/foot.handlebars"))
        .pipe(gulp.dest('./build/serverViews/includes'));

so the injected files look like this:

<script src="/build/js/app.js"></script>

my problem is that my files are reachable on /js/app.js and not on /build/js/app.js

is there a way to a achieve this?

Injecting files to dest based on src filename

Lets say I have a sign-up.html file and I created a sign-up.scss file that I want to compile and pipe into the injector to inject into my html file. But I only want it to inject the sign-up.css file into the sign-up.html file and no other .hmtl files that have the injector block. Is there a way to do this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.