Giter Club home page Giter Club logo

gulp-inline's Introduction

gulp-inline

Information

Build Status codecov npm version

Packagegulp-inline
DescriptionInlines js/css/svg into your html files
Node Version= 0.10

Usage

var inline = require('gulp-inline')
  , uglify = require('gulp-uglify')
  , minifyCss = require('gulp-minify-css')
  , autoprefixer = require('gulp-autoprefixer');

gulp.src('public/index.html')
  .pipe(inline({
    base: 'public/',
    js: uglify,
    css: [minifyCss, autoprefixer({ browsers:['last 2 versions'] })],
    disabledTypes: ['svg', 'img', 'js'], // Only inline css files
    ignore: ['./css/do-not-inline-me.css']
  }))
  .pipe(gulp.dest('dist/'));

Replaces your <script> and <link> tags with the corresponding inlined files.

SVG support

Currently there are two supported methods:

  • <img> element with src attribute:

    <img src="/assets/icon.svg" class="MyClass" />
    

    which will be converted to something like

    <svg xmlns="http://www.w3.org/2000/svg" viewbox="..." class="MyClass">
      <circle ... />
      <path ... />
      etc.
    </svg>
    

    depending on what /assets/icon.svg contains

  • <svg> element with <use> child element:

    <svg>
      <use xlink:href="/assets/icon.svg#MyIdentifier"></use>
    </svg>
    

    Note that this method requires an ID matching the ID of target SVG root element.

    This is valid target SVG for the example above:

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" id="MyIdentifier">
      ...
    </svg>
    

    while this is invalid:

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
      ...
    </svg>
    

Options

Plugin options:

  • base - the root directory containing the files to be inlined
  • css - css transform (gulp plugin)
  • js - js transform (gulp plugin)
  • svg - svg transform (gulp plugin)
  • ignore - array of file paths to ignore and not inline (file paths as they appear in the source)
  • disabledTypes - array of types not to run inlining operations on (css, svg, js, img)

How to set options for uglify when used as plugin

Below is an example of how to pass options to uglify. In this case we tell uglify to not mangle function names.

var inline = require('gulp-inline')
  , uglify = require('gulp-uglify');

gulp.src('public/index.html')
  .pipe(inline({
    base: 'public/',
    js: function() {
      return uglify({
          mangle: false
      });
    }
  }))
  .pipe(gulp.dest('dist/'));

gulp-inline's People

Contributors

ashaffer avatar brknrobot avatar cehoffman avatar chris-oreilly avatar indolering avatar ivkos avatar jonnyscholes avatar kihlstrom avatar maxkoryukov avatar pdonald avatar rafaelnco avatar sergeylukin avatar simonzack avatar vanwagenenj 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

Watchers

 avatar  avatar  avatar  avatar  avatar

gulp-inline's Issues

Not to fix html

source:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

after inline

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Document</title>
    <style>
        body {}
    </style>
</head>
<body>
</body></html>

The last line is unnecessary

Gulp inline changing case of custom attributes in HTML markup

I have a Gulp task to inline CSS and JS into my HTML file:

gulp.task('html', function () {
    gulp.src(source + '**/*.+(html|php)')
    .pipe($.plumber())
    .pipe($.inline({
        base: source,
        disabledTypes: ['svg', 'img']
    }))
    .pipe(gulp.dest(build))
    .pipe(reload({
        stream: true
    }));
});

I'm finding that the inline plugin is making changes to my HTML markup. Most noticeably it is changing the case of attributes.

mktoName="Banner Heading" becomes mktoname="Banner Heading"

Is there a fix for this?

I tried adding html to the disabledType options, but this did nothing?
I cannot change the casing of the name of this attribute, it related to marketo templates

Thanks

Skipping over JS

It will inline my CSS, but the JS is untouched! The JS, CSS, and HTML are in the exact same folder....


  gulp.src('./src/index.html')
    .pipe(inline({
      base: 'src/'
    }))
    .pipe(gulp.dest("./test/"));

<!doctype html>

<head>
    <meta charset="utf-8">

    <title>Speech.is</title>
    <link href="style.css" rel="stylesheet" type="text/css" media="all">

    <script src="init.js"></script>
    <script>
        transformURI(window.location, function(err, uri){
            if(err && err['name'] === "redirect"){
                window.location = err['redirect']; // forward to -> www.jsdns.tld
            } else if(err){
                Fail(err);
            } else {
                window['uri'] = uri;
            }
        })
    </script>

    <script src="libs/pouchdb/dist/pouchdb-nightly.js"></script>
    <script src="DNS.js"></script>
    <script>
        new DNS(null, null, function(err, dns){
            if(err) Fail(err);

            window['dns'] = dns;
            dns.lookup(window['uri'].name, function(err, record){
                if(err) Fail(err);

                if(window['nav']){
                    window['nav'].load(record, window['uri']);
                } else {
                    window['record'] = record;
                }
            })
        })
    </script>

</head>
<body>
<iframe id="speech" seamless width="100%" allowfullscreen="true" src="">
</iframe>

<script src=Nav.js></script>


<script>

 window['nav'] = new Nav(document.getelementbyid('speech'));
 if(window['record']){
     window.nav.load(window['record'], window['uri']);
 }

</script>

<script src=paint.js></script>

<script>
 updater(document.getelementbyid('speech'));
 resizer(document.getelementbyid('speech'));
</script>

</body>
</html>

Stay attributes

Stay attributes exept src/link etc.

<script src="config.js" some-attr="someOption"></script>

//after inlining
<script some-attr="someOption">
    //config.js content
</script>

Support user-defined custom tags in `typeMap`

I'd love to be able to use gulp-inline to inline different content types based on user-defined tag definitions.

In my case, I need to inline Polymer web component definitions (via <link rel="import"> tags) – but I can see this being really handy for more application-specific use cases (e.g. a custom <i18n key="foo"> tag definition).

Any chance of allowing a custom typeMap to be passed as an option?

Problem with non-value attributes?

I'm running this on an index.html generated by angular-cli (ng build):

let gulp = require('gulp')
let inline = require('gulp-inline')

gulp.task('inline', async function () {
    await gulp.src('dist/index.html')
    .pipe(inline({
        base: 'dist/',
        disabledTypes: 'css, svg, img'
    }))
    .pipe(gulp.dest('dist/'));
});

Some script tags are created as following:
<script src="runtime-es5.1eba213af0b233498d9d.js" nomodule defer>

But the result looks like that:
<script nomodule="defer="></script>

Remove gulp-util from dependecies.

Today I started using gulp-inline for my work, however, it gave me an error, that it has a dependency on a package called gulp-util, which in its place is deprecated and should not be used. Here is the URL that I followed from the warning message. But I don't know what I can do it fix it. Any alternatives for gulp-inline maybe?

image

add cache option

I can generate some content manually. F.e. I use config.js for local work, but for production I use other config. It would be good to put some files contents in the cache. Moreover, the use of cache (cache: true) optimizes inlining files repeatedly.

.pipe(inline({
    cache: {
        'config.js': 'my content'
    }
}))

svg inline is altering html and php markup

I am finding that certain html and php markup is being converted when running inline for svgs.
The main issue is converting html and html strings in php variables to self closing tags

Is this due to the svg being converted to short tags?

Is there a way I can prevent this from happening?
I found a useShortTag setting for SVGO
svg/svgo#396

Is there a way to pass additional parameters to a transform plugin, similar to the pretty parameters?
https://www.npmjs.com/package/gulp-svgmin#beautify

I've also looked in to the cheerio load settings
https://github.com/cheeriojs/cheerio#loading

Specifically I think this is to do with concatenated strings and html a tag such as:
'<h1>' . $my_content . '</h1>';
which gets converted to
'<h1>' . $my_content . '';

TypeError: Cannot read property 'toString' of null

Sometimes have this error.

D:\test\amrest-app\node_modules\gulp-inline\index.js:50
  el.attr('src', 'data:image/unknown;base64,' + contents.toString('base64'))
                                                        ^

TypeError: Cannot read property 'toString' of null
    at typeMap.img.template (D:\test\amrest-app\node_modules\gulp-inline\index.js:50:61)
    at Transform._transform (D:\test\amrest-app\node_modules\gulp-inline\index.js:211:20)
    at Transform._read (D:\test\amrest-app\node_modules\gulp-inline\node_modules\through2\node_modules\readable-stream\lib\_stream_transform.js:184:10)
    at Transform._write (D:\test\amrest-app\node_modules\gulp-inline\node_modules\through2\node_modules\readable-stream\lib\_stream_transform.js:172:12)
    at doWrite (D:\test\amrest-app\node_modules\gulp-inline\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:237:10)
    at writeOrBuffer (D:\test\amrest-app\node_modules\gulp-inline\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:227:5)
    at Transform.Writable.write (D:\test\amrest-app\node_modules\gulp-inline\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:194:11)
    at write (D:\test\amrest-app\node_modules\vinyl-fs\node_modules\readable-stream\lib\_stream_readable.js:623:24)
    at flow (D:\test\amrest-app\node_modules\vinyl-fs\node_modules\readable-stream\lib\_stream_readable.js:632:7)
    at DestroyableTransform.pipeOnReadable (D:\test\amrest-app\node_modules\vinyl-fs\node_modules\readable-stream\lib\_stream_readable.js:664:5)

Fixed only after several remove/install node_modules, rebootings.
My gulpfile.js: https://github.com/g1un/amrest-app/blob/master/gulpfile.js

Support RegEx for ignored files

We rename our *.js files for cache busting, e.g. the file my-file.js becomes my-file-<HASH>.js. Today, it's not possible to exclude files from gulp-inline without knowing their precise filename.

Hence, it would be great to allow regular expressions in the list of ignored files, e.g.:

inline({
  base: 'dist/',
  ignore: [
    'my-file-.*.js'
  ]
})

href='//hoge.com' makes error

if src , href values likes "//hoge.com(with out http or https)"

makes

function isLocal(href) {
return href && ! url.parse(href).hostname;
}

return false all time and make error...

so please fix this bug

How about <object> ?

Instead of img element with src attribute or svg element with use child element I`m actually using object element in my development environment. However, theres still no support for object element inlining. Is it something that hard to do? Is there any way I can contribute to this?

Duplicate JS

You appear to be inlining the same scripts:

gulp.task('inlinetest', function(){
  gulp.src('./src/test.html')
    .pipe(inline({
      base: 'src/'
    }))
    .pipe(gulp.dest("./spx/"));
});

test.html

<!DOCTYPE html>
<html>
<head>
  <script src="foo.js"  type='text/javascript'></script>
  <script src="bar.js"  type='text/javascript'></script>
</head>
<body>

<script>
  foo();
  bar();
</script>

</body>
</html>

foo.js

function foo(){
  console.log("foo");
}

bar.js

function bar(){
  console.log("bar");
}

output

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript">
function foo(){
  console.log("foo");
}
</script>
  <script type="text/javascript">
function foo(){
  console.log("foo");
}
</script>
</head>
<body>

<script>
  foo();
  bar();
</script>

</body>
</html>

Add synchronous method

var inline = require('gulp-inline')

var processedContent = inline.sync(content, baseUrl, options);
//or
var processedVinylFile = inline.sync(vinylFile, options);

It is useful for some situation. F.e. if I processindex.html I don't need to create a stream for a single file

function buildProject(options) {
    function transform(file, enc, callback) {
        //Transform each .js/.css/.html file
    }

    function flush(callback) {
        //It is more comfortable then use gulp.src(indexPath).pipe(inline()).pipe(someCompileFn())
        var indexContent = fs.readFileSync(path.join(options.baseUrl, 'index.html'));
        var compiledIndex = new gutil.File({
            path: newIndexPath,
            contents: new Buffer(inline.sync(indexContent , options.baseUrl), 'utf8');
        }) 
        this.push(compiledIndex);
    }

    return through.obj(transform, flush)
}

css url paths not changed

source:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Document</title>
    <link rel="stylesheet" href="./css/style.css">
</head>
<body>

style.css:

@font-face{
    src: url(../fonts/xx.ttf)
}
body{
    background-image: url(../img/x.jpg)
}

where style.css was in the folder named "css"

after inline

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Document</title>
    <style>
        @font-face{
            src: url(../fonts/xx.ttf)
        }
        body{
             background-image: url(../img/x.jpg)
        }
    </style>
</head>
<body>
</body></html>

css is now in "main" folder (it is in html)
same path to url files, while it shouldn't be

Not closing some svg tags

Input :

<line></line>
<ellipse></ellipse>
<path></path>
<polyline></polyline>
<div></div>
<randomtag></randomtag>

Output :

<line>
<ellipse>
<path>
<polyline></polyline>
<div></div>
<randomtag></randomtag>

Is this happening on purpose? If so, it is breaking the display of svgs.

Love the project, thanks for sharing it!

Upgrade cheeriojs and option for decodeEntities: false

I had a problem using this plugin because it changed some qoutes in a inline eventlistener

<div id="Banner" onclick="window.open('website', 'new window')">

became

<div id="Banner" onclick="window.open(&apos;website&apos;, &apos;new window&apos;)">

I found after som digging that it was cheerio that modified the qoutes. Cheerio have a option for decodeEntities when set to false don't change the qoutes. This option is only added in a newer version than the one used in gulp-inline at the moment.

so i propose to upgrade cheerio and maybe make a option to set the setting in the gulp-inline plugin. og change the standard option.

Skipping over CSS

<template>
  <core-selection id="selection" multi="{{multi}}" on-core-select="{{selectedHandler}}"></core-selection>
  <link rel="stylesheet" type="text/css" href="../bower_components/bower_components/core-list/core-list.css">
  <div id="viewport" class="core-list-viewport"><content></content></div>
</template>

It's skipping over the above CSS stylesheet. Any guesses as to why?

Duplicate CSS

When inlining multiple CSS files, one of them gets duplicated for all of them.

gulpfile:

gulp.task('inline', function () {
    return gulp.src('src/test.html')
        .pipe(inline({
            base: 'src/',
            css: minifyCss()
        }))
        .pipe(gulp.dest(paths.dest));
});

test.html:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="css/default.css" />
    <link rel="stylesheet" type="text/css" href="css/print.css" media="print" />
    <!-- ... -->
</head>
<body>
    <!-- ... -->
</body>

default.css

.showOnPrint {
    display: none;
}

print.css

.showOnPrint {
    display: block;
}

output

<!DOCTYPE html>
<html>
<head>
    <style>
    .showOnPrint {display: block;}
    </style>
    <style>
    .showOnPrint {display: block;}
    </style>
    <!-- ... -->
</head>
<body>
    <!-- ... -->
</body>

It consistently duplicates one of the files, but it's not consistent in which one it duplicates. I imagine this issue is similar to Issue #7 just for CSS.

Multiple js/css transforms?

Is it possible to define more than one js and css transform? That would be really helpful.

Not working example:

js: uglify(), concat()
css: minifyCss(), autoPrefixer('last 2 version'), unCss()

js and css plugin options

How do I initiate js and css plugin options?

.pipe($.inline({
    base: source,
    js: $.uglify,
    css: $.cleanCss({
        keepBreaks: false,
        advanced: false,
        aggressiveMerging: false
    }),
    disabledTypes: ['svg', 'img']
}))

CSS Doesn't Support Media Attribute

When including CSS with a specific media attribute, the media attribute is removed after the file is inlined.

<link rel="stylesheet" type="text/css" href="css/globalPrint.css" media="print" />

becomes

<style>/* styles */</style>

how to skip some js/css files?

IMO, some common files should NOT be embed into HTML, could I use some attributes to skip being inline like what grunt-embed did?

Ive got that JS could be skipped if ignore the attribute of type, but I have no ideabout how to skip the CSS?

SVG elements are not being inlined

I'm not having any luck getting SVG elements to be inlined. I'm using the <svg /> tag as described in the README:

<svg>
  <use xlink:href="./visa-logo.svg#visa-logo"/>
</svg>

And the first line of ./visa-logo.svg (which is in the same directory) is:

<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 75.785455" height="75.785454"
  width="200" xml:space="preserve" version="1.1" id="visa-logo">

However when I run the task the element is being ignored? The JS and CSS files are however being inlined.

Any advice?

When I use gulp-inline for Freemarker

for example:

the freemarker is:

<#macro duraTip>
</#macro>

after gulp-inline

<#macro duratip=""><!-- quotation mark. -->
</#macro>

the 'duraTip' has quotation mark....

Replacing all apostrophe's with &apos;

in v0.0.9

It is replacing apostrophe's in the HTML file (not necessarily the JS or CSS files).

For instance, in template.html, prior to running inline:

<title>David's Site</title>

After running inline successfully:

<title>David's Site</title>

I've debugged it down to inline being the cause -- I did notice a closed issue with this problem though?

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.