Giter Site home page Giter Site logo

wc-loader's Introduction

WC Loader

Webcomponents webpack loader . Supports hot code reload. ๐Ÿšฝ ๐Ÿ˜œ

DEMO - https://github.com/aruntk/polymer-webpack-demo

Polymer Webpack Apollo-Graphql Demo - https://github.com/aruntk/githunt-polymer

About

wc-loader helps you use webcomponents (polymer, x-tags etc also) with webpack.

Under the hood

wc-loader uses parse5 which parses HTML the way the latest version of your browser does. Does not use any regex to parse html. :)

Main functions
  1. Handles html link imports. With Hot Code Reload Support
  2. Handles external script files (script src). With Hot Code Reload Support
  3. Handles external css files (link rel stylesheet)
  4. Handles template tags.
  5. Removes comments and unecessary whitespaces.
  6. Handles loading order of html and js inside the polymer files
  7. Adds components to document during runtime.

Installation

npm i -D wc-loader

Usage

module: {
    rules: [
      {
        test: /\.js$/, // handles js files. <script src="path.js"></script> and import 'path';
        use: [{
          loader: 'babel-loader',
        }],
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/, // handles assets. eg <img src="path.png">
        use: [{
          loader: 'file-loader',
          options: {
            name: '[name].[ext]?[hash]'
          }
        }]
      },
      {
        test: /\.html$/, // handles html files. <link rel="import" href="path.html"> and import 'path.html';
        use: [
          // if you not using es6 inside html remove babel-loader
          {

            loader: 'babel-loader',
            // similarly you can use coffee, typescript etc.
          },
          {
            loader: 'wc-loader',
            options: {
              minify: true,
            },
          }]
      },
    ],
  ]
}

Using es6, typescript, coffee etc inside html

In the following config

{
  test: /\.html$/,
  use: [
    {
      loader: 'babel-loader', // change this line
    },
    {
      loader: 'wc-loader',
      options: {
        minify: true,
      },
    }]
},

if you are using es6 inside html use

loader: 'babel-loader'

similarly you can use coffee, typescript etc. pipe wc result through the respective loader.

loader: 'ts-loader'
loader: 'coffee-loader'

Options

You can either specify options as part of the loader string or as options property

{
  loader: 'wc-loader',
  options: {
    minify: true
  }
}

'Root-relative' URLs

For urls that start with a /, the default behavior is to not translate them. You'll get a file not found error in the browser. (/path = example.com/path for the browser) If a root query parameter is set, however, it will be prepended to the url and then translated.

<!-- file.html -->
<img src="/image.jpg">
// webpack config. options.root can also be used

loader: 'wc-loader?root=/absolue/path/to/root/folder'

// or

loader: 'wc-loader?root=' + path.resolve('relative/path/to/root/folder')

// example

loader: 'wc-loader?root=/'

Minify html

loader: 'wc-loader?minify=true'

default options are

const defaultMinifierOptions = {
  collapseWhitespace: true,
  customAttrAssign: [/\$=/],
  ignoreCustomFragments: [/style\$?="\[\[.*?\]\]"/],
}

Use custom options - by config setting minifierOptions

Refer https://github.com/kangax/html-minifier for more info

options: {
   minify: true,
   minifierOptions: {
     // custom options
   }
}

Like it?

โญ this repo

Found a bug?

Raise an issue!

License

MIT. Check licence file.

wc-loader's People

Contributors

0xr avatar 4esnog avatar aruntk avatar leonrodenburg 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

wc-loader's Issues

Does not support quotes in urls in css

Code like this is not supported:

  @font-face {
    font-family: "MyFont";
    src: url("MyFont.woff");
  }

It results in this error:

Module not found: Error: Can't resolve './"MyFont.woff"' in 'some/dir/on/machine'

Seems like a quick fix in processStyles.

Support for webpack@4

Seems like wc-loader is incompatible with webpack@4

Here is the output of webpack build:

ERROR in ./assets/web-components/tags-select/tags-select.html
Module build failed: TypeError: Cannot read property 'output' of undefined
    at Object.convertPlaceholder (/Users/nchesnokov/tv-projects/data-issues/node_modules/wc-loader/dist/index.js:370:96)
    at Object.module.exports (/Users/nchesnokov/tv-projects/data-issues/node_modules/wc-loader/dist/index.js:434:22)
 @ ./assets/web-components/tags-select/tags-select.js 1:0-60
 @ ./assets/entries/report/report.js

ES6 transpiling + WC loader not working

I have tried to use this syntax as the readme says

loader: 'babel-loader!wc-loader'

WC loader works, but the resulting Javascript code isn't transpiled, the Babel loader is already configured, as I added WC loader on an existing workflow.

I will put a quick repo ASAP to reproduce the issue, but if you have some quick tip it is welcome.

thanks

Does not work for AppLocalizeBehavior

Hi, I tried wc-loader for one of my projects and stumbled upon an issue with AppLocalizeBehavior. If I have a Polymer component that references app-localize-behavior, then my application breaks with the following console error:

Uncaught ReferenceError: IntlMessageFormat is not defined

In another application, the error is a bit different, but seems to boil down to the same core issue (I have not found out, yet, what causes the different error message here):

Uncaught TypeError: Cannot set property 'IntlMessageFormat' of undefined

I have set up an example application based on the wc-loader demo app: https://github.com/emrass/polymer-webpack-demo

app-localize-behavior.html links a minified js file of the intl package. This is translated to a

require('../intl-messageformat/dist/intl-messageformat.min.js');

by wc-loader. From here on, I'm lost and don't know what causes the issue. I'll try to dig deeper, but would love to get your insights into the issue. Thanks!

Unbundled dev mode with wc-loader

I'm using wc-loader to bundle my Polymer elements, and it's working flawlessly.

However, is there a way I can bundle each component's resources (html, js, and css) into one file, but keep the different components separate, and not bundle them together, and especially not bundle them with the Polymer library itself? I need this for debugging, where instead of loading a single 20,000 LOC file in the devtools, I need to load one specific component I need to debug.
Is this doable?

style tags are not handled properly

This code fails

case 'style':
            {
              if (child.childNodes && child.childNodes.length) {
                var childNode = child.childNodes[0];
                var css = childNode.value;
                var _result = self.processStyle(css);
                if (_result) {
                  childNode.value = _result;
                }
              }
              return child;
            }

processStyles takes 2 argumens, so the second is undefined and gets passed to path.dirname which fails in recent versions of node.

Won't the code replacing urls in styles break anything? E.g. I have the following.

      .number text.clipped {
        z-index: 4;
        fill: var(--text-primary-color);
        clip-path: url('#handClip');
      }

What is the expected behavior?

ModuleNotFoundError with css external assets. How to handle css assets?

Hi, i have this css snippet inside my web component:

:host {
  display: flex;
  contain: content;
  position: relative;
  overflow: hidden;
  background-image: url("/assets/images/thread-row-placeholder.svg");
}

I get this error:

Module not found: Error: Can't resolve '/assets/images/thread-row-placeholder.svg'
Module build failed: ModuleNotFoundError: Module not found: Error: Can't resolve '/assets/images/thread-row-placeholder.svg'

How do you suppose to handle external assets in css?

Atm i have to comment out this portion of the lib to get things work.

var processed = text.replace(/url\(["']?((?!.*:\/\/|"|'|\)).+?)["']?\)/ig, function (_u, url) {
    // to get -> filepath from url(filepath), url('filepath') and url('filepath')
    return 'url(' + self._changeRelUrl(url, _path2.default.dirname(cssBasePath)) + ')';
});
return processed;

I'm on webpack 3.4.1 and wc-loader 1.1.9

Code is generated to load whitespace

Using the webpack analyze tool I discovered that sometimes code like this is generated:

/*__wc__loader*/

(function (document) {
  var _htmlStr = "\n\n\n\n\n\n\n\n\n\n\n\n\n";
  if (document.head) {
    var el = document.head;
    var div = document.createElement('div');
    div.innerHTML = _htmlStr;
    while (div.children.length > 0) {
      el.appendChild(div.children[0]);
    }
  } else {
    document.write(_htmlStr);
  }
})(document);

(function (document) {
  var _htmlStr = "<dom-module ...

This seems unnecessary and not doing this will improve runtime performance and bundle size.

import behaviors looks incorrect

When some component imports file with <script> tag that contains behavior in some object, loader fails to load this script properly. For example:
<link rel="import" href="chart-property-behavior.html">
where chart-property-behavior is:

<script>
  var ChartBehaviors = ChartBehaviors || {};
  /** @polymerBehavior */
  ChartBehaviors.ChartPropertyBehavior = {
  ...
</script>

When i try to load a page i get an error Uncaught ReferenceError: ChartBehaviors is not defined, because it inserts script after this component and within module. Component from chart-elements.

Is there any possible workaround?

Creating extra <dom-module> element

wc-loader is a great module, after compiled the HTML file it is creating dom-module tags in DOM for each polymer component.

Is that a problem with wc-loader?

Externally hosted web components?

Does this work with externally hosted web components?

For example, would this externally hosted hello-world component be packaged?

<html>
  <link ref="import" href="https://example.com/components/hello-world.html">
</html>

I did a test, and it seems, like it was not packaged by default.

What would it take to make this work?

Support for <link rel="stylesheet"> with an SCSS target

Is it possible to combine wc-loader with sass-loader?

I have currently a work around by referencing my stylesheet from my dist folder after processing scss with sass-loader and using ExtractTextPlugin.

It would be ne nice if you could simply use

    <link rel="stylesheet" href="my.scss">

inside the webcomponents.

Regards
Florian

Tries to access publicPath of undefined

screen shot 2017-05-02 at 21 00 39

This is what I have in my webpack config:

  output: 
   { path: '/Users/Birowsky/Projects/Commercial/Dscova/Dscova - Frontend/builds/web',
     publicPath: '',
     filename: '[name].js' },

Let me know if I can provide anything else helpful. Note that I have no idea how loaders are implemented.

Thanx!

Cannot resolve module 'wc'

I'm trying to use your loader but it wont work, probably something I have done. ๐Ÿ˜„

Error in   Error: Child compilation failed:
  Module not found: Error: Cannot resolve module 'wc' in /private/var/www/path/to/components:

In my index.html i have the link tags that imports the web components

<link rel="import" href="../xcomp/components/xc-blanks.html" />

Loader fails to compile polymer.html

Hello

I am facing issues with the wc-loader. See error message here

ERROR in Error: Child compilation failed:
Module not found: Error: Can't resolve './bower_components/polymer/polymer.html' in '/Users/vinayakam.murugan/Projects/demo-pwa/src':
Error: Can't resolve './bower_components/polymer/polymer.html' in '/Users/vinayakam.murugan/Projects/demo-pwa/src'
Module not found: Error: Can't resolve './bower_components/webcomponentsjs/webcomponents-lite.js' in '/Users/vinayakam.murugan/Projects/demo-pwa/src':
Error: Can't resolve './bower_components/webcomponentsjs/webcomponents-lite.js' in '/Users/vinayakam.murugan/Projects/demo-pwa/src'
Module not found: Error: Can't resolve './custom_components/media-list/media-list.html' in '/Users/vinayakam.murugan/Projects/demo-pwa/src':
Error: Can't resolve './custom_components/media-list/media-list.html' in '/Users/vinayakam.murugan/Projects/demo-pwa/src'

Here is the base project with an older webpack config -
https://github.com/simpleharshit/demo-pwa

Attached is my latest webpack config.

webpack.config.js.zip

How to use lib when importing in index.html with HtmlWebpackPlugin

Hi guys
Short question: I have an index.html that imports my web components with html imports. Like: <link rel="import" href="bower_components/app-layout/app-layout.html">
Also I am working in an angular project so my html webpack config looks like this:

            {
                test: /\.html$/,
                loader: 'html-loader'
            },

And I use HtmlWebpackPlugin to import the index.html, like this:

        new HtmlWebpackPlugin({
            template: 'index.html'
        })

How should I include the wc-loader in this setup?

Loader fails?

I have an app.html file which contains the following code: <link rel="import" href="../bower_components/paper-button/paper-button.html"> and I have import './app.html'; in my index.js. This however results in:

You may need an appropriate loader to handle this file type.
| <link rel="import" href="../bower_components/paper-button/paper-button.html">

This is my webpack config: https://gist.github.com/drager/fa08ec7d252f54124b0880dac779b6ca

Child combinator in CSS is replaced with &gt;

I'm using styles inside of <template> via <link>:

<template>
	<link rel="stylesheet" href="./tags-select.css" />
	...
</template>

This <link> is being replaced with <style> tag, which contains styles from my file.

As I can see, the issue is that parse5.serialize() replaces all css child combinators (.parent > .child) with &gt; (.parent &gt; .child).
Obviously, it breaks my styles.

Exclude img files?

Is it possible to exclude img files?

This is in my webpack 2 config

module: {
        rules: [{
            test: /\.html$/, 
            use: ['wc-loader'],
            exclude: /(png|jpg|gif|svg)/,
        }, {
            test: /\.js$/,
            exclude: /(node_modules|scripts)/,
            use: [{
                loader: 'babel-loader',
                options: {
                    presets: ['es2015']
                }
            }],
        }, {
            test: /\.(sass|scss)$/,
            use: [
                'style-loader',
                'css-loader',
                'sass-loader',
            ]
        }]
    }

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.