Code Monkey home page Code Monkey logo

html-loader's Introduction

npm node tests coverage discussion size

html-loader

Exports HTML as string. HTML is minimized when the compiler demands.

Getting Started

To begin, you'll need to install html-loader:

npm install --save-dev html-loader

or

yarn add -D html-loader

or

pnpm add -D html-loader

Then add the plugin to your webpack config. For example:

file.js

import html from "./file.html";

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: "html-loader",
      },
    ],
  },
};

Options

sources

Type:

type sources =
  | boolean
  | {
      list?: Array<{
        tag?: string;
        attribute?: string;
        type?: string;
        filter?: (
          tag: string,
          attribute: string,
          attributes: string,
          resourcePath: string,
        ) => boolean;
      }>;
      urlFilter?: (
        attribute: string,
        value: string,
        resourcePath: string,
      ) => boolean;
      scriptingEnabled?: boolean;
    };

Default: true

By default every loadable attribute (for example - <img src="image.png">) is imported (const img = require('./image.png') or import img from "./image.png""). You may need to specify loaders for images in your configuration (recommended asset modules).

Supported tags and attributes:

  • the src attribute of the audio tag
  • the src attribute of the embed tag
  • the src attribute of the img tag
  • the srcset attribute of the img tag
  • the src attribute of the input tag
  • the data attribute of the object tag
  • the src attribute of the script tag
  • the href attribute of the script tag
  • the xlink:href attribute of the script tag
  • the src attribute of the source tag
  • the srcset attribute of the source tag
  • the src attribute of the track tag
  • the poster attribute of the video tag
  • the src attribute of the video tag
  • the xlink:href attribute of the image tag
  • the href attribute of the image tag
  • the xlink:href attribute of the use tag
  • the href attribute of the use tag
  • the href attribute of the link tag when the rel attribute contains stylesheet, icon, shortcut icon, mask-icon, apple-touch-icon, apple-touch-icon-precomposed, apple-touch-startup-image, manifest, prefetch, preload or when the itemprop attribute is image, logo, screenshot, thumbnailurl, contenturl, downloadurl, duringmedia, embedurl, installurl, layoutimage
  • the imagesrcset attribute of the link tag when the rel attribute contains stylesheet, icon, shortcut icon, mask-icon, apple-touch-icon, apple-touch-icon-precomposed, apple-touch-startup-image, manifest, prefetch, preload
  • the content attribute of the meta tag when the name attribute is msapplication-tileimage, msapplication-square70x70logo, msapplication-square150x150logo, msapplication-wide310x150logo, msapplication-square310x310logo, msapplication-config, twitter:image or when the property attribute is og:image, og:image:url, og:image:secure_url, og:audio, og:audio:secure_url, og:video, og:video:secure_url, vk:image or when the itemprop attribute is image, logo, screenshot, thumbnailurl, contenturl, downloadurl, duringmedia, embedurl, installurl, layoutimage
  • the icon-uri value component in content attribute of the meta tag when the name attribute is msapplication-task

boolean

The true value enables the processing of all default elements and attributes, the false value disables the processing of all attributes.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: "html-loader",
        options: {
          // Disables attributes processing
          sources: false,
        },
      },
    ],
  },
};

object

Allows you to specify which tags and attributes to process, filter them, filter urls and process sources starting with /.

For example:

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: "html-loader",
        options: {
          sources: {
            list: [
              // All default supported tags and attributes
              "...",
              {
                tag: "img",
                attribute: "data-src",
                type: "src",
              },
              {
                tag: "img",
                attribute: "data-srcset",
                type: "srcset",
              },
            ],
            urlFilter: (attribute, value, resourcePath) => {
              // The `attribute` argument contains a name of the HTML attribute.
              // The `value` argument contains a value of the HTML attribute.
              // The `resourcePath` argument contains a path to the loaded HTML file.

              if (/example\.pdf$/.test(value)) {
                return false;
              }

              return true;
            },
          },
        },
      },
    ],
  },
};

list

Type:

type list = Array<{
  tag?: string;
  attribute?: string;
  type?: string;
  filter?: (
    tag: string,
    attribute: string,
    attributes: string,
    resourcePath: string,
  ) => boolean;
}>;

Default: supported tags and attributes.

Allows to setup which tags and attributes to process and how, as well as the ability to filter some of them.

Using ... syntax allows you to extend default supported tags and attributes.

For example:

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: "html-loader",
        options: {
          sources: {
            list: [
              // All default supported tags and attributes
              "...",
              {
                tag: "img",
                attribute: "data-src",
                type: "src",
              },
              {
                tag: "img",
                attribute: "data-srcset",
                type: "srcset",
              },
              {
                // Tag name
                tag: "link",
                // Attribute name
                attribute: "href",
                // Type of processing, can be `src` or `scrset`
                type: "src",
                // Allow to filter some attributes
                filter: (tag, attribute, attributes, resourcePath) => {
                  // The `tag` argument contains a name of the HTML tag.
                  // The `attribute` argument contains a name of the HTML attribute.
                  // The `attributes` argument contains all attributes of the tag.
                  // The `resourcePath` argument contains a path to the loaded HTML file.

                  if (/my-html\.html$/.test(resourcePath)) {
                    return false;
                  }

                  if (!/stylesheet/i.test(attributes.rel)) {
                    return false;
                  }

                  if (
                    attributes.type &&
                    attributes.type.trim().toLowerCase() !== "text/css"
                  ) {
                    return false;
                  }

                  return true;
                },
              },
            ],
          },
        },
      },
    ],
  },
};

If the tag name is not specified it will process all the tags.

You can use your custom filter to specify html elements to be processed.

For example:

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: "html-loader",
        options: {
          sources: {
            list: [
              {
                // Attribute name
                attribute: "src",
                // Type of processing, can be `src` or `scrset`
                type: "src",
                // Allow to filter some attributes (optional)
                filter: (tag, attribute, attributes, resourcePath) => {
                  // The `tag` argument contains a name of the HTML tag.
                  // The `attribute` argument contains a name of the HTML attribute.
                  // The `attributes` argument contains all attributes of the tag.
                  // The `resourcePath` argument contains a path to the loaded HTML file.

                  // choose all HTML tags except img tag
                  return tag.toLowerCase() !== "img";
                },
              },
            ],
          },
        },
      },
    ],
  },
};

Filter can also be used to extend the supported elements and attributes.

For example, filter can help process meta tags that reference assets:

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: "html-loader",
        options: {
          sources: {
            list: [
              {
                tag: "meta",
                attribute: "content",
                type: "src",
                filter: (tag, attribute, attributes, resourcePath) => {
                  if (
                    attributes.value === "og:image" ||
                    attributes.name === "twitter:image"
                  ) {
                    return true;
                  }

                  return false;
                },
              },
            ],
          },
        },
      },
    ],
  },
};

Note

source with a tag option takes precedence over source without.

Filter can be used to disable default sources.

For example:

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: "html-loader",
        options: {
          sources: {
            list: [
              "...",
              {
                tag: "img",
                attribute: "src",
                type: "src",
                filter: () => false,
              },
            ],
          },
        },
      },
    ],
  },
};

urlFilter

Type:

type urlFilter = (
  attribute: string,
  value: string,
  resourcePath: string,
) => boolean;

Default: undefined

Allow to filter urls. All filtered urls will not be resolved (left in the code as they were written). Non-requestable sources (for example <img src="javascript:void(0)">) are not handled by default.

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: "html-loader",
        options: {
          sources: {
            urlFilter: (attribute, value, resourcePath) => {
              // The `attribute` argument contains a name of the HTML attribute.
              // The `value` argument contains a value of the HTML attribute.
              // The `resourcePath` argument contains a path to the loaded HTML file.

              if (/example\.pdf$/.test(value)) {
                return false;
              }

              return true;
            },
          },
        },
      },
    ],
  },
};

scriptingEnabled

Type:

type scriptingEnabled = boolean;

Default: true

By default, the parser in html-loader interprets content inside <noscript> tags as #text, so processing of content inside this tag will be ignored.

In order to enable processing inside <noscript> for content recognition by the parser as #AST, set this parameter to: false

Additional information: scriptingEnabled

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: "html-loader",
        options: {
          sources: {
            // Enables processing inside the <noscript> tag
            scriptingEnabled: false,
          },
        },
      },
    ],
  },
};

preprocessor

Type:

type preprocessor = (
  content: string | Buffer,
  loaderContext: LoaderContext,
) => HTMLElement;

Default: undefined

Allows pre-processing of content before handling.

Warning

You should always return valid HTML

file.hbs

<div>
  <p>{{firstname}} {{lastname}}</p>
  <img src="image.png" alt="alt" />
<div>

function

You can set the preprocessor option as a function instance.

webpack.config.js

const Handlebars = require("handlebars");

module.exports = {
  module: {
    rules: [
      {
        test: /\.hbs$/i,
        loader: "html-loader",
        options: {
          preprocessor: (content, loaderContext) => {
            let result;

            try {
              result = Handlebars.compile(content)({
                firstname: "Value",
                lastname: "OtherValue",
              });
            } catch (error) {
              loaderContext.emitError(error);

              return content;
            }

            return result;
          },
        },
      },
    ],
  },
};

You can also set the preprocessor option as an asynchronous function instance.

For example:

webpack.config.js

const Handlebars = require("handlebars");

module.exports = {
  module: {
    rules: [
      {
        test: /\.hbs$/i,
        loader: "html-loader",
        options: {
          preprocessor: async (content, loaderContext) => {
            let result;

            try {
              result = await Handlebars.compile(content)({
                firstname: "Value",
                lastname: "OtherValue",
              });
            } catch (error) {
              await loaderContext.emitError(error);

              return content;
            }

            return result;
          },
        },
      },
    ],
  },
};

minimize

Type:

type minimize =
  | boolean
  | {
      caseSensitive?: boolean;
      collapseWhitespace?: boolean;
      conservativeCollapse?: boolean;
      keepClosingSlash?: boolean;
      minifyCSS?: boolean;
      minifyJS?: boolean;
      removeComments?: boolean;
      removeRedundantAttributes?: boolean;
      removeScriptTypeAttributes?: boolean;
      removeStyleLinkTypeAttributes?: boolean;
    };

Default: true in production mode, otherwise false

Tell html-loader to minimize HTML.

boolean

The enabled rules for minimizing by default are the following ones:

({
  caseSensitive: true,
  collapseWhitespace: true,
  conservativeCollapse: true,
  keepClosingSlash: true,
  minifyCSS: true,
  minifyJS: true,
  removeComments: true,
  removeRedundantAttributes: true,
  removeScriptTypeAttributes: true,
  removeStyleLinkTypeAttributes: true,
});

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: "html-loader",
        options: {
          minimize: true,
        },
      },
    ],
  },
};

object

webpack.config.js

See html-minifier-terser's documentation for more information on the available options.

The default rules can be overridden using the following options in your webpack.conf.js

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: "html-loader",
        options: {
          minimize: {
            removeComments: false,
            collapseWhitespace: false,
          },
        },
      },
    ],
  },
};

The default rules can be extended:

webpack.config.js

const { defaultMinimizerOptions } = require("html-loader");

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: "html-loader",
        options: {
          minimize: {
            ...defaultMinimizerOptions,
            removeComments: false,
            collapseWhitespace: false,
          },
        },
      },
    ],
  },
};

esModule

Type:

type esModule = boolean;

Default: true

By default, html-loader generates JS modules that use the ES modules syntax. There are some cases in which using ES modules is beneficial, such as module concatenation and tree shaking.

You can enable a CommonJS modules syntax using:

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: "html-loader",
        options: {
          esModule: false,
        },
      },
    ],
  },
};

Examples

Disable url resolving using the <!-- webpackIgnore: true --> comment

With <!-- webpackIgnore: true --> comment, one can disable sources handling for next tag.

<!-- Disabled url handling for the src attribute -->
<!-- webpackIgnore: true -->
<img src="image.png" />

<!-- Disabled url handling for the src and srcset attributes -->
<!-- webpackIgnore: true -->
<img
  srcset="image.png 480w, image.png 768w"
  src="image.png"
  alt="Elva dressed as a fairy"
/>

<!-- Disabled url handling for the content attribute -->
<!-- webpackIgnore: true -->
<meta itemprop="image" content="./image.png" />

<!-- Disabled url handling for the href attribute -->
<!-- webpackIgnore: true -->
<link rel="icon" type="image/png" sizes="192x192" href="./image.png" />

roots

With resolve.roots one can specify a list of directories where requests of server-relative URLs (starting with '/') are resolved.

webpack.config.js

module.exports = {
  context: __dirname,
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: "html-loader",
        options: {},
      },
      {
        test: /\.jpg$/,
        type: "asset/resource",
      },
    ],
  },
  resolve: {
    roots: [path.resolve(__dirname, "fixtures")],
  },
};

file.html

<img src="/image.jpg" />
// => image.jpg in __dirname/fixtures will be resolved

CDN

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.jpg$/,
        type: "asset/resource",
      },
      {
        test: /\.png$/,
        type: "asset/inline",
      },
    ],
  },
  output: {
    publicPath: "http://cdn.example.com/[fullhash]/",
  },
};

file.html

<img src="image.jpg" data-src="image2x.png" />

index.js

require("html-loader!./file.html");

// => '<img src="http://cdn.example.com/49eba9f/a992ca.jpg" data-src="image2x.png">'
require('html-loader?{"sources":{"list":[{"tag":"img","attribute":"data-src","type":"src"}]}}!./file.html');

// => '<img src="image.jpg" data-src="data:image/png;base64,..." >'
require('html-loader?{"sources":{"list":[{"tag":"img","attribute":"src","type":"src"},{"tag":"img","attribute":"data-src","type":"src"}]}}!./file.html');

// => '<img src="http://cdn.example.com/49eba9f/a992ca.jpg" data-src="data:image/png;base64,..." >'

Process script and link tags

script.file.js

console.log(document);

style.file.css

a {
  color: red;
}

file.html

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Title of the document</title>
    <link rel="stylesheet" type="text/css" href="./style.file.css" />
  </head>
  <body>
    Content of the document......
    <script src="./script.file.js"></script>
  </body>
</html>

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/,
        type: "asset/resource",
        generator: {
          filename: "[name][ext]",
        },
      },
      {
        test: /\.html$/i,
        use: ["html-loader"],
      },
      {
        test: /\.js$/i,
        exclude: /\.file.js$/i,
        loader: "babel-loader",
      },
      {
        test: /\.file.js$/i,
        type: "asset/resource",
      },
      {
        test: /\.css$/i,
        exclude: /\.file.css$/i,
        loader: "css-loader",
      },
      {
        test: /\.file.css$/i,
        type: "asset/resource",
      },
    ],
  },
};

Templating

You can use any template system. Below is an example for handlebars.

file.hbs

<div>
  <p>{{firstname}} {{lastname}}</p>
  <img src="image.png" alt="alt" />
<div>

webpack.config.js

const Handlebars = require("handlebars");

module.exports = {
  module: {
    rules: [
      {
        test: /\.hbs$/i,
        loader: "html-loader",
        options: {
          preprocessor: (content, loaderContext) => {
            let result;

            try {
              result = Handlebars.compile(content)({
                firstname: "Value",
                lastname: "OtherValue",
              });
            } catch (error) {
              loaderContext.emitError(error);

              return content;
            }

            return result;
          },
        },
      },
    ],
  },
};

PostHTML

You can use PostHTML without any additional loaders.

file.html

<img src="image.jpg" />

webpack.config.js

const posthtml = require("posthtml");
const posthtmlWebp = require("posthtml-webp");

module.exports = {
  module: {
    rules: [
      {
        test: /\.hbs$/i,
        loader: "html-loader",
        options: {
          preprocessor: (content, loaderContext) => {
            let result;

            try {
              result = posthtml().use(plugin).process(content, { sync: true });
            } catch (error) {
              loaderContext.emitError(error);

              return content;
            }

            return result.html;
          },
        },
      },
    ],
  },
};

Export into HTML files

A very common scenario is exporting the HTML into their own .html file, to serve them directly instead of injecting with javascript. This can be achieved with a combination of html-loader and asset modules.

The html-loader will parse the URLs, require the images and everything you expect. The extract loader will parse the javascript back into a proper html file, ensuring images are required and point to proper path, and the asset modules will write the .html file for you. Example:

webpack.config.js

module.exports = {
  output: {
    assetModuleFilename: "[name][ext]",
  },
  module: {
    rules: [
      {
        test: /\.html$/,
        type: "asset/resource",
        generator: {
          filename: "[name][ext]",
        },
      },
      {
        test: /\.html$/i,
        use: ["html-loader"],
      },
    ],
  },
};

Contributing

Please take a moment to read our contributing guidelines if you haven't yet done so.

CONTRIBUTING

License

MIT

html-loader's People

Contributors

akesser avatar alexander-akait avatar anshumanv avatar avraammavridis avatar cap-bernardito avatar dependabot[bot] avatar ersachin3112 avatar eslamhiko avatar evilebottnawi avatar filipesilva avatar fire-dragon-dol avatar harish-sethuraman avatar hemanth avatar jhnns avatar joshwiens avatar kevinzwhuang avatar laland avatar larrifax avatar latentflip avatar markmontymark avatar michael-ciniawsky avatar mkoopmanatadobe avatar morhetz avatar nuragic avatar rajkissu avatar rax7 avatar ryanclark avatar sebastianomorando avatar snitin315 avatar sokra 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

html-loader's Issues

Angular template html load by html-loader will error, if webpack use parameter -p

In angular directive, I load template by require('./template.html')
for example:
return {
restrict: 'AE',
priority: 1,
scope: { gridModel: '=eeTree'},
template: require('./template.html'),
link: function ($scope, element, attrs) {}
}
if template.html file contain {{ a<b }}, there will error happen, html-loader or webpack think '<' mean html tag start symbol.
this error only happen by use parameter -p to pack

Integrate with css-loader css module support

This is a feature request.

I'd like to be able to compile a template which can require in CSS Modules and apply the dynamic class names to elements. Essentially something like this:

<link href="./headers.css" rel="stylesheet:headers" />
<link href="./layout.css" rel="stylesheet:layout" />

<div class="layout.card layout.flex">
    <h1 class="headers.main">My styled header<h1>
</div>

Basically the :headers and :layout parts name local vars which store your dynamic class name maps. They are then accessed by referencing var.class where var is the name of the local var you gave it in the link tag and class is a class name from that file as it appeared in the source.

Obviously the syntax is flexible, but I like that this approximates current tags and their usages. What's more CSS class names cannot have . characters and link tag rel attributes do not contain : characters, so this syntax should be safe from unintended consequences. It could also add entirely new tags and attributes to handle this.

Why do this?

I know that ES6 templates tags and common frameworks like React and Angular provide ways to do all this in JavaScript, eliminating the need for this. I am wanting to add this to provide a migration path for a legacy codebase to use CSS Modules (which I โค๏ธ BTW). In my particular case, I'm having a JSP tag read in the HTML (via extract-text-webpack-plugin) and use it in its server side generation with a long term goal of migrating server side rendering to React/Angular 2.

I love these new technologies and I wouldn't even need something like this in a green field project. But when working out a migration strategy for existing code, options like these are invaluable.

css-loader, style-loader and company would figure out how to load the actual CSS to the page, this just handles dynamic class name insertion.

I would love to work on the PR for this, if this is something the maintainers would want. If not I can look at writing a separate loader to do the same thing.

Thoughts? Love it? Hate it? I'd love to have a discussion. ๐Ÿ˜„

need to support ES6 module

I'm using webpack 2.0 beta, if I want to " import xx from 'x.css' ", then pass xx string to the template config(like template: xx), running will go wrong cause the build will be: " template: xx.default ", however htmlloader build will be : "module.exports=xx", not "module['default']=xx".

Shim webpack imports of HTML/CSS while in Mocha tests

I write my Angular applications as ES6 for WebPack, where one might do:

import SomeTemplate from "./template.html";
import "./some.css";

This works fine when combining Webpack and Babel, because Webpack affects the stream before Babel translates. But I also want to unit test my code, using Mocha and Babel. When I import the above, I get the two errors below.

It's to be expected, although I'm not sure why Babel by default interprets .html as React. Just wondering, what's the right way to shim this in tests? Do I need to write a plugin for my tests that intercepts imports of HTML and CSS and does nothing?

The HTML loading gives::

/Users/paul/projects/karl/admin5/src/admin/box/box.showlog.html:3
React.createElement(
^

ReferenceError: React is not defined
    at Object.<anonymous> (/Users/paul/projects/karl/admin5/src/admin/box/box.showlog.html:1:1)
    at Module._compile (module.js:430:26)
    at normalLoader (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:199:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:216:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/paul/projects/karl/admin5/src/admin/box/box.list.controller.js:1:14)
    at Module._compile (module.js:430:26)
    at normalLoader (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:199:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:216:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/paul/projects/karl/admin5/src/admin/box/tests/box.list.controller.specs.js:5:27)
    at Module._compile (module.js:430:26)
    at normalLoader (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:199:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:216:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at /Users/paul/projects/karl/admin5/node_modules/mocha/lib/mocha.js:192:27
    at Array.forEach (native)
    at Mocha.loadFiles (/Users/paul/projects/karl/admin5/node_modules/mocha/lib/mocha.js:189:14)
    at Mocha.run (/Users/paul/projects/karl/admin5/node_modules/mocha/lib/mocha.js:422:31)
    at Object.<anonymous> (/Users/paul/projects/karl/admin5/node_modules/mocha/bin/_mocha:398:16)
    at Module._compile (module.js:430:26)
    at Object.Module._extensions..js (module.js:448:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:471:10)
    at startup (node.js:117:18)
    at node.js:952:3

...and the CSS gives::

SyntaxError: /Users/paul/projects/karl/admin5/src/admin/admin.css: Unexpected token (2:11)
  1 | 
> 2 | md-sidenav a {
    |            ^
  3 |     text-decoration: none;
  4 | }
  5 | 
    at Parser.pp.raise (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/node_modules/babylon/lib/parser/location.js:24:13)
    at Parser.pp.unexpected (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/node_modules/babylon/lib/parser/util.js:82:8)
    at Parser.pp.semicolon (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/node_modules/babylon/lib/parser/util.js:69:81)
    at Parser.pp.parseExpressionStatement (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/node_modules/babylon/lib/parser/statement.js:427:8)
    at Parser.parseExpressionStatement (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/node_modules/babylon/lib/plugins/flow.js:642:20)
    at Parser.pp.parseStatement (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/node_modules/babylon/lib/parser/statement.js:142:21)
    at Parser.parseStatement (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/node_modules/babylon/lib/plugins/flow.js:621:22)
    at Parser.pp.parseTopLevel (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/node_modules/babylon/lib/parser/statement.js:30:21)
    at Parser.parse (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/node_modules/babylon/lib/parser/index.js:70:17)
    at Object.parse (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/node_modules/babylon/lib/index.js:45:50)
    at Object.exports.default (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/helpers/parse.js:36:18)
    at File.parse (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/transformation/file/index.js:573:40)
    at File.parseCode (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/transformation/file/index.js:690:20)
    at /Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/transformation/pipeline.js:167:12
    at File.wrap (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/transformation/file/index.js:638:16)
    at Pipeline.transform (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/transformation/pipeline.js:165:17)
    at Object.transformFileSync (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/api/node.js:137:37)
    at compile (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:132:20)
    at normalLoader (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:199:14)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:216:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/paul/projects/karl/admin5/src/admin/box/box.list.controller.js:1:14)
    at Module._compile (module.js:430:26)
    at normalLoader (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:199:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:216:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/paul/projects/karl/admin5/src/admin/box/tests/box.list.controller.specs.js:5:27)
    at Module._compile (module.js:430:26)
    at normalLoader (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:199:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/paul/projects/karl/admin5/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:216:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at /Users/paul/projects/karl/admin5/node_modules/mocha/lib/mocha.js:192:27
    at Array.forEach (native)
    at Mocha.loadFiles (/Users/paul/projects/karl/admin5/node_modules/mocha/lib/mocha.js:189:14)
    at Mocha.run (/Users/paul/projects/karl/admin5/node_modules/mocha/lib/mocha.js:422:31)
    at Object.<anonymous> (/Users/paul/projects/karl/admin5/node_modules/mocha/bin/_mocha:398:16)
    at Module._compile (module.js:430:26)
    at Object.Module._extensions..js (module.js:448:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:471:10)
    at startup (node.js:117:18)
    at node.js:952:3

Errror when try to to use with img src

Whats I doing wrong?

JS Controller

import '../../assets/messaginghub.png';

HTML

<img src="messaginghub.png" style="margin-bottom: -12px; height: 60px" />

Webpack configuration

{test: /\.png$/i, loader: 'url?mimetype=image/png&name=imgs/[name].[ext]?[hash]', exclude: /node_modules/},
{test: /\.html$/, loader: 'html', exclude: /node_modules/}

Error

ERROR in ./~/html-loader!./www/components/anon/loginView.html
Module not found: Error: Cannot resolve 'file' or 'directory' ./\"" in ...\www\components\anon
 @ ./~/html-loader!./www/components/anon/loginView.html 1:1186-1205

sem titulo

open="true" minimized to open, how to prevent

Hi. I have original code "<..... open="true" ....>", when I build my project and html loader minimizes HTML - I get "<......... open ........>". But I do not want such behavior. Could you please recommend how to set params to loader and which params certainly?

Angular2 directives <*ng-if="octocat"> breaks when prod

When running webpack in prod mode -p an error occurs when using directives such as *ng-if because of the * that somehow breaks html-loader.

ERROR in ./lib/components/http/index.html
Module build failed:
 @ ./lib/components/http/index.ts 34:22-45

If you want to test you can clone https://github.com/shprink/angular2-nobullshit-boilerplate/ and change the raw loader by the html loader in this line: https://github.com/shprink/angular2-nobullshit-boilerplate/blob/master/webpack.config.js#L28

HTML imports

Are there any plans or ideas how to support html-imports?

I guess this would also require to tackle the problem how to include referenced scripts and stylesheets into the bundle.

about the Template7 {{js}}

hello!

text.html

<a href="#" class=" {{js "this.type === \'page\' ? \'back\' : \'\'"}}"></a>

when i run build! this html cant load! but i can require this in webpack-dev-server!

my format does not comply with it?

Forgive my bad English.. = =!!

Add License.md

Is the code licensed with MIT ?

Can you please add a file in the repository (and update the package.json)

default minification settings are dangerous

By default, this plugin will blow away 'redundant' attributes. This means that it will remove type='text' from an input. This is bad because it breaks styles, and potentially javascript etc.

The html minifier you use has settings that it calls "safe", you should default to those at most.

Documentation for `minimize` option

Continued from #34 (comment) - I should have made a new issue in the first place, my bad.

Anyway, my question is where is the minimize option documented? Are there options I can pass to it? Is it on or off by default? I have looked up and down the docs, but I only saw the comment about --optimize-minimize which I'm not sure does anything ๐Ÿ˜•

After looking through the source a bit, I've enabled it explicitly with:

htmlLoader: {
  minimize: true
}

but I'm not really sure if there is a difference being made on the HTML I'm loading in (via other loaders in the pipeline).

Ignore hash fragments in URLs

When an HTML page is referencing URLs containing hash fragments, html-loader will extract the entire URL and attempt to require it. This obviously fails, as no such URL (including the hash fragment) exists. A real world use case would be when a HTML page is using inline-svg with an external source, like this:

<svg viewBox="0 0 100 100">
    <use xlink:href="icons.svg#icon-arrow"></use>
</svg>

In this case, html-loader will turn the href-attribute into something similar to this require("./icons.svg#icon-arrow"), which causes webpack to crash, as the correct result should have been something like this require("./icons.svg") + "#icon-arrow"

Template syntax issue stalls webpack build when using UglifyJsPlugin

When using the following syntax in the template and running webpack -p or webpack --optimize-minimize the build progress stalls at "build modules" and never completes, no error, no timeout, no nothing .. just hangs there.

<a @click="doSomething"></a>

While this works without a problem:

<a v-on:click="doSomething"></a>

The syntax is used as a vue.js shorthand for attaching event listeners to elements.
vuejs/vue-loader#102

Should fastparse be moved into loader-utils?

I'm working on adding some features to handlebars-loader, and one of the things I want to add is the ability to insert requires for static assets w/in the templates, or static assets referenced in helper parameters.

The fastparse library looks like it would do what I need, but I'd rather not straight-up copy it from this repo. It seems like it's generic enough to include in loader utils - what do you think? Or, it could be its own repo. I think parseAttributes is fine to stay in here, though I could also see that moving to loader utils as well. What do you think?

Interpolate Option Outputs Javascript with HTML

I'm using the interpolate option, var mytemplate = require('html?interpolate!./mytemplate.html'), to include 'partials' in my html file

mytemplate.html

<div>
${require(./partials/mypartial.html)}
</div>

partials/mypartial.html

In a partial

The partial get appropriately loaded but the resulting html string (mytemplate) has the html wrapped in module.exports("HTML_FILE_HERE");

The final result would place the string 'module.exports("<div>In a partial</div>")' in the variable mytemplate. I want it to be simply the html, which is the way it isually is if I don't have the option interpolate option turned on for the require.

What am I doing wrong, or is this a bug?

Support minification

A feature for discussion:

The loader by default should not alter the included file. This would be useful during development, to see the included content with comments, indentation, etc.

But there should be a way to minimize it when packaging for distribution.

Option to integrate with i8n plugin?

This isn't an issue, but really a feature request. I would love to use this loader in conjunction with the internationalization plugin. The internationalization plugin is sweet, but it only works in Javascript and if any of you are like my company, almost all our textual content is written in the html, making the plugin essentially useless. However, if the html parser could be intelligent enough to look for i8n attributes (in the same way it looks for img src attributes), then this problem could be effectively solved.

Imagine a use scenario like so:

//An html file: someText.html
<div>
    <h1>Company Name</h1>
    <div i8n> Some text <b> with bold </b></div>
 </div>

//Then gets converted to this webpack module...
module.exports = "<div> <h1> Company Name </h1> <div i8n>" + __("Some text <b> with bold </b>") + "</div></div>"

I think this could work, although it would be very dependent on the implementation of the i8n plugin. There also might be some snags in ensuring the loader escapes special characters in the html and disallows nested i8n attributes. But in all, it might not be too bad assuming the i8n plugin plays nicely.

Would people be opposed to adding this feature?

Suggest adding explicit support for framework templates

The current settings will break Angular 2 templates as well as templates for many other MVC frameworks. Rather than try to require uses to pass custom ignore regex's it would be better to have a framework query:

html?framework=Angular2 or html?framework=Ember, etc that ensured the minification settings were safe by default for those frameworks. I'm happy to put together pull requests for Angular and Angular2.

http://perfectionkills.com/html-minifier-revisited/

Test HTML comment minification

Minification should remove HTML comments. Changing loaderTest.js test "should minimize" to look like this:

'<!-- comment --><h3>#{number} {customer}</h3>\n<p>   {title}   </p>\n\t <!-- comment --> <img src="image.png" />'

Should still produce the same result.

I've made this modification on the test:

diff --git a/test/loaderTest.js b/test/loaderTest.js
index f2fd67f..66978f5 100644
--- a/test/loaderTest.js
+++ b/test/loaderTest.js
@@ -37,8 +37,8 @@ describe("loader", function() {
        it("should minimize", function() {
                loader.call({
                        minimize: true
-               }, '<h3>#{number} {customer}</h3>\n<p>   {title}   </p>\n\t<img src="image.png" />').should.be.eql(
+               }, '<!-- comment --><h3>#{number} {customer}</h3>\n<p>   {title}   </p>\n\t <!-- comment --> <img src="image.png" />').should.be.eql(
                        'module.exports = "<h3>#{number} {customer}</h3><p>{title}</p><img src=" + require("./image.png") + ">";'
                );
        });
-});
\ No newline at end of file
+});

After running mocha I get this error:

  1) loader should minimize:

      AssertionError: expected 'module.exports = "<!-- comment --><h3>#{number} {customer}</h3><p>{title}</p><!-- comment --><img src=" + require("./image.png") + ">";' to equal 'module.exports = "<h3>#{number} {customer}</h3><p>{title}</p><img src=" + require("./image.png") + ">";'
      + expected - actual

      +"module.exports = \"<h3>#{number} {customer}</h3><p>{title}</p><img src=\" + require(\"./image.png\") + \">\";"
      -"module.exports = \"<!-- comment --><h3>#{number} {customer}</h3><p>{title}</p><!-- comment --><img src=\" + require(\"./image.png\") + \">\";"

      at Assertion.prop.(anonymous function) (/home/fernando/work/github/webpack/html-loader/node_modules/should/lib/should.js:60:14)
      at Context.<anonymous> (/home/fernando/work/github/webpack/html-loader/test/loaderTest.js:40:132)
      at Test.Runnable.run (/usr/lib/node_modules/mocha/lib/runnable.js:221:32)
      at Runner.runTest (/usr/lib/node_modules/mocha/lib/runner.js:374:10)
      at /usr/lib/node_modules/mocha/lib/runner.js:452:12
      at next (/usr/lib/node_modules/mocha/lib/runner.js:299:14)
      at /usr/lib/node_modules/mocha/lib/runner.js:309:7
      at next (/usr/lib/node_modules/mocha/lib/runner.js:247:23)
      at Object._onImmediate (/usr/lib/node_modules/mocha/lib/runner.js:276:5)
      at processImmediate [as _immediateCallback] (timers.js:330:15)

I couldn't find a configuration option to activate HTML comment removal.

Loading riot templates not working after upgrade

I've been using this loader for riot templates and noticed that on upgrade from 0.4.0 to 0.4.2 all my onclick bindings stopped working. In riot I define them like this:

onclick="{ onClick }"

Any idea why it doesn't work anymore? I'd need those to stay unchanged in the loaded string.

Minifier Errors need to be reported during build

During the build process, if you have an error in your html code (for instance <div role-"nav">lorem</div>, the - when it should be =), instead of reporting the error and stopping the larger webpack build process, the process just hangs.

If it's at all possible, the minifier should error out and report the error to webpack for display to the user.

error path for img src attribute.

template

<img src="images/test.png" />

js

require('./template.html')

But webpack cannot find module.

Uncaught Error: Cannot find module "./images/default_food.png"

Turns out html-loader translate the template to

"<img src=\"" + require("./images/default_food.png") + "\" />"

But what I want is require("images/default_food.png"). no ./ prepended.

Add issue and pull request templates

Bring html-loader project documentation inline with webpack core

  • Modify and add ISSUE_TEMPLATE.md from webpack/webpack
  • Modify and add PULL_REQUEST_TEMPLATE.md from webpack/webpack
  • Add LICENSE
  • Add CONTRIBUTING.md

Support <link href=""/>

Wanting to use it with a template that has this in the head tag:

<link rel="apple-touch-icon" href="icon.png"/>

But it doesn't seem to pick it up! The syntax seems simple enough to add.. want a pull request?

Can i set a variable img src?

Because i am using the html-loader as my template loader, sometimes i need to set a variable img src like

<img src="[[key]].png"/>

But it will cause en error telling that the img cannot be found, i think the url-loader is trying to find it.

Any solution about this?

How can I copy a video file

loader:
{ test: /\.jade$/, loader: 'html?attrs[]=img:src!jade-html?doctype=html' }

jade:
video(autoplay,loop,id="bgvid")
source(src="/assets/frames.mp4",type="video/mp4")

Support partial HTML markup

A feature for discussion:

I propose the loader should have an option not to require a full HTML document, within <html> tags.

I'd like to use the html loader to load an HTML snippet (representing a template) as text into a variable.

The snippet would look like this:

<!-- List item template. -->
<li>
  <a href="#">
    <h3>#{number} {customer}</h3>
    <p>{title}</p>
    <span class="ui-li-count">{status}</span> <!-- shows status -->
    <p class="ui-li-aside"><strong>{time}</strong></p>
  </a>
</li>

And I would include it like this:

var listTemplate = require('html!templates/listItem.html');

Currently I'm doing that using the raw loader, but I'd like to be able to keep including templates but to have other HTML-specific options (specially minification).

How to use this with file loader?

How can I use html-loader together with file-loader, so I can preprocess image urls by wepback and then generate output to html file?

'root-relative' urls are not resolved correctly

I'm having an issue with webpack failing to resolve a 'root-relative' url for a img src in an html file. When code looks something like (/project/app/index.html):

<img src="/app/assets/img.jpg" />

webpack says:

ModuleNotFoundError: Module not found: Error: Cannot resolve file or directory .//app/assets/img.jpg in /project/app

[v0.5.5] minimize=false not being respected

I'm setting the html-loader query to minimize=false in my webpack config, but when bundled for production and uglyfied, html is still getting compressed (eg. whitespace removed, input type=text remove, etc). Any ideas how to work around this? I'd love to use uglify as part of webpack and not a seperate build step.

Allow to inline scripts and styles

would be nice if the loader converted <script src... and <script>...</script> to requires.

Not sure how to achieve the multiple javascript output from a single module, though.

Pretty print/multi-line output

I was wondering about a way to create a more "diffable" output... for easier line-by-line auditing of the generated JavaScript.

Perhaps there could be an option to have multi-line output like this?

module.exports = [
    "<div>\n",
    "    <p>Just a thought...</p>\n",
    "</div>\n",
].join('');

Obviously our templates a little bigger than this or else I would not be asking...

minification removes all spaces between tags

This means potential layout issues between development and production since whitespace is significant in html. Rather than eliminating them entirely, spaces should be collapsed to a single sequential space to better reflect how html is handled by browsers.

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.