GithubHelp home page GithubHelp logo

posthtml-loader's Introduction

npm node deps tests coverage code style chat

PostHTML Loader

Install

npm i -D posthtml-loader

Usage

import html from './file.html'

webpack.config.js

module: {
  rules: [
    {
      test: /\.html$/,
      use: [
        'html-loader',
        {
          loader: 'posthtml-loader',
          options: {
            ident: 'posthtml',
            parser: 'PostHTML Parser',
            plugins: [
              /* PostHTML Plugins */
              require('posthtml-plugin')(options)
            ]
          }
        }
      ]
    }
  ]
},

Options

Name Type Default Description
config {Object} undefined PostHTML Config
parser {String/Function} undefined PostHTML Parser
skipParse {Boolean} false PostHTML Options SkipParse
render {String/Function} undefined PostHTML Render
plugins {Array/Function} [] PostHTML Plugins
sync {boolean} false PostHTML Options Sync
directives {Array<Object>} [] PostHTML Options custom Directives

Config

Name Type Default Description
path {String} loader.resourcePath PostHTML Config Path
ctx {Object} {} PostHTML Config Context

If you want to use are shareable config file instead of inline options in your webpack.config.js create a posthtml.config.js file and place it somewhere down the file tree in your project. The nearest config relative to dirname(file) currently processed by the loader applies. This enables Config Cascading. Despite some edge cases the config file will be loaded automatically and no additional setup is required. If you don't intend to use Config Cascading, it's recommended to place posthtml.config.js in the root ./ of your project

src
├── components
│   ├──  component.html
│   ├──  posthtml.config.js (components)
├── index.html
├── posthtml.config.js (index)
└── webpack.config.js

Path

If you normally place all your config files in a separate folder e.g ./config it is necessary to explicitly set the config path in webpack.config.js

webpack.config.js

{
  loader: 'posthtml-loader',
  options: {
    config: {
      path: 'path/to/.config/'
    }
  }
}

Context

Name Type Default Description
env {String} 'development' process.env.NODE_ENV
file {Object} { dirname, basename, extname } File
options {Object} {} Plugin Options (Context)

posthtml.config.js

module.exports = ({ file, options, env }) => ({
  parser: 'posthtml-sugarml',
  plugins: {
    'posthtml-include': options.include,
    'posthtml-content': options.content,
    'htmlnano': env === 'production' ? {} : false
  }
})

webpack.config.js

{
  loader: 'posthtml-loader',
  options: {
    config: {
      ctx: {
        include: {...options},
        content: {...options}
      }
    }
  }
}

Parser

If you want to use a custom parser e.g SugarML, you can pass it in under the parser key in the loader options

{String}

webpack.config.js

{
  loader: 'posthtml-loader',
  options: {
    parser: 'posthtml-sugarml'
  }
}

{Function}

webpack.config.js

{
  loader: 'posthtml-loader',
  options: {
    parser: require('posthtml-sugarml')()
  }
}

skipParse

If you want to use disable parsing, you can pass it in under the skipParse key in the loader options

{Boolean}

webpack.config.js

{
  loader: 'posthtml-loader',
  options: {
    skipParse: false
  }
}

Render

If you want to use a custom render, you can pass it in under the render key in the loader options

{String}

webpack.config.js

{
  loader: 'posthtml-loader',
  options: {
    render: 'posthtml-you-render'
  }
}

{Function}

webpack.config.js

{
  loader: 'posthtml-loader',
  options: {
    parser: require('posthtml-you-render')()
  }
}

Plugins

Plugins are specified under the plugins key in the loader options

{Array}

webpack.config.js

{
  loader: 'posthtml-loader',
  options: {
    plugins: [
      require('posthtml-plugin')()
    ]    
  }
}

{Function}

webpack.config.js

{
  loader: 'posthtml-loader',
  options: {
    plugins (loader) {
      return [
        require('posthtml-plugin')()
      ]
    }
  }
}

Sync

Enables sync mode, plugins will run synchronously, throws an error when used with async plugins

{Boolean}

webpack.config.js

{
  loader: 'posthtml-loader',
  options: {
    sync: true
  }
}

Directives

If you want to use a custom directives, you can pass it in under the directives key in the loader options

{Array}

webpack.config.js

{
  loader: 'posthtml-loader',
  options: {
    directives: [{name: '?php', start: '<', end: '>'}]
  }
}

Maintainer


Michael Ciniawsky

Ivan Demidov

posthtml-loader's People

Contributors

btkostner avatar dependabot[bot] avatar greenkeeperio-bot avatar jescalan avatar michael-ciniawsky avatar scrum avatar tinymachine 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

Watchers

 avatar  avatar  avatar  avatar  avatar

posthtml-loader's Issues

Set posthtml expression options

When I try to add posthtml expression options then it fail:

options: {
              plugins: [
                require("posthtml-expressions")({
                  removeScriptLocals: true 
                }),
                require("posthtml-extend")({
                  encoding: "utf8",
                  root: "./src/"
                }),
              ],
            },

Error:

ERROR in Error: Child compilation failed:
Module build failed (from ./node_modules/posthtml-loader/lib/index.js):
PostHTML Loader:

SyntaxError: Unexpected identifier

  at node_modules/posthtml-loader/lib/index.js:158:10

ModuleBuildError: Module build failed (from ./node_modules/posthtml-loader/lib/index.js):

Compiled template issue

The compiled template are wrapped with module-exports = "...html code here..."

What am I doing wrong?

Screenshot 2022-01-21 at 10 37 48

How can I use plugins that work with images if the html loader does not give them links?

I want to use plugins posthtml posthtml-webp, but I can't it, because html-loader give a source without a pre-render of images.
More accurately, I understand, that html loader located after post html loader, but I don't understand, how i can work with images, because posthtml does not understand syntax: <img src="~Images/quickly.svg">

I need that html-loader give a html source <img src="432e9ad6d54da6ffc62a.svg"> (rendered) and I will use a posthtml loader, but If I will do it, will errors.
Screenshot_3

How to check if a variable is set?

Suppose we have a variable for set body class.
In case we don't pass any variable as body class I get class="undefined"

How to check if variable is set?

Like:

<body class="{{ if(bodyClass) bodyClass }}">
or
<body class="{{ bodyClass ? bodyClass : 'default' }}">

watch posthtml.config.js

Watch the config file and trigger rebuild (hotreload) when changed

posthtmlrc(ctx, ctx.dir).then((config) => {
   loader.addDependencyTo(config.file)
   delete require.cache(config.file)
   return config
})

require() is not a function

On using plugins with the posthtml-loader using a posthtml.config.js or stating the configuration directly in the webpack.config.js, I constantly get a TypeError: require(...) is not a function.

  - ModuleBuildError: Module build failed (from ../node_modules/posthtml-loader/lib/index.js):
  
  - PostHTML Loader:
  
  - require(...) is not a function
  

❌ Error (Logs|Stacks)

Using posthtml.config.js:

TypeError: require(...) is not a function
at load (/home/apollo/posthtml-loader-require-bug/node_modules/posthtml-load-config/lib/plugins.js:40:31)
at /home/apollo/posthtml-loader-require-bug/node_modules/posthtml-load-config/lib/plugins.js:51:18
at Array.forEach ()
at plugins (/home/apollo/posthtml-loader-require-bug/node_modules/posthtml-load-config/lib/plugins.js:50:8)
at /home/apollo/posthtml-loader-require-bug/node_modules/posthtml-load-config/index.js:66:18
TypeError: Cannot read properties of undefined (reading 'default')
at /home/apollo/posthtml-loader-require-bug/node_modules/posthtml-load-config/lib/plugins.js:53:20
at Array.forEach ()
at plugins (/home/apollo/posthtml-loader-require-bug/node_modules/posthtml-load-config/lib/plugins.js:50:8)
at /home/apollo/posthtml-loader-require-bug/node_modules/posthtml-load-config/index.js:66:18
TypeError: require(...) is not a function
at load (/home/apollo/posthtml-loader-require-bug/node_modules/posthtml-load-config/lib/plugins.js:40:31)
at /home/apollo/posthtml-loader-require-bug/node_modules/posthtml-load-config/lib/plugins.js:51:18
at Array.forEach ()
at plugins (/home/apollo/posthtml-loader-require-bug/node_modules/posthtml-load-config/lib/plugins.js:50:8)
at /home/apollo/posthtml-loader-require-bug/node_modules/posthtml-load-config/index.js:66:18
TypeError: Cannot read properties of undefined (reading 'default')
at /home/apollo/posthtml-loader-require-bug/node_modules/posthtml-load-config/lib/plugins.js:53:20
at Array.forEach ()
at plugins (/home/apollo/posthtml-loader-require-bug/node_modules/posthtml-load-config/lib/plugins.js:50:8)
at /home/apollo/posthtml-loader-require-bug/node_modules/posthtml-load-config/index.js:66:18

Using webpack.config.js

ERROR in ./index.html
Module build failed (from ./node_modules/posthtml-loader/lib/index.js):
PostHTML Loader:

require(...) is not a function

at /home/apollo/posthtml-loader-require-bug/node_modules/posthtml-loader/lib/index.js:158:10

@ ./index.js 1:0-32

ERROR in Error: Child compilation failed:
Module build failed (from ./node_modules/posthtml-loader/lib/index.js):
PostHTML Loader:

require(...) is not a function

  at /home/apollo/posthtml-loader-require-bug/node_modules/posthtml-loader/lib/index.js:158:10

ModuleBuildError: Module build failed (from ./node_modules/posthtml-loader/lib/index.js):
PostHTML Loader:

require(...) is not a function

  at /home/apollo/posthtml-loader-require-bug/node_modules/posthtml-loader/lib/index.js:158:10
  at processResult (/home/apollo/posthtml-loader-require-bug/node_modules/webpack/lib/NormalModule.js:753:19)
  at /home/apollo/posthtml-loader-require-bug/node_modules/webpack/lib/NormalModule.js:855:5
  at /home/apollo/posthtml-loader-require-bug/node_modules/loader-runner/lib/LoaderRunner.js:399:11
  at /home/apollo/posthtml-loader-require-bug/node_modules/loader-runner/lib/LoaderRunner.js:251:18
  at context.callback (/home/apollo/posthtml-loader-require-bug/node_modules/loader-runner/lib/LoaderRunner.js:124:13)
  at /home/apollo/posthtml-loader-require-bug/node_modules/posthtml-loader/lib/index.js:158:7
  • index.js:158
    [posthtml-loader-require-bug]/[posthtml-loader]/lib/index.js:158:10

  • ModuleBuildError: Module build failed (from ./node_modules/posthtml-loader/lib/index.js):

  • PostHTML Loader:

  • require(...) is not a function

  • index.js:158
    [posthtml-loader-require-bug]/[posthtml-loader]/lib/index.js:158:10

  • NormalModule.js:753 processResult
    [posthtml-loader-require-bug]/[webpack]/lib/NormalModule.js:753:19

  • NormalModule.js:855
    [posthtml-loader-require-bug]/[webpack]/lib/NormalModule.js:855:5

  • LoaderRunner.js:399
    [posthtml-loader-require-bug]/[loader-runner]/lib/LoaderRunner.js:399:11

  • LoaderRunner.js:251
    [posthtml-loader-require-bug]/[loader-runner]/lib/LoaderRunner.js:251:18

  • LoaderRunner.js:124 context.callback
    [posthtml-loader-require-bug]/[loader-runner]/lib/LoaderRunner.js:124:13

  • index.js:158
    [posthtml-loader-require-bug]/[posthtml-loader]/lib/index.js:158:7

  • child-compiler.js:169
    [posthtml-loader-require-bug]/[html-webpack-plugin]/lib/child-compiler.js:169:18

  • Compiler.js:564
    [posthtml-loader-require-bug]/[webpack]/lib/Compiler.js:564:11

  • Compiler.js:1183
    [posthtml-loader-require-bug]/[webpack]/lib/Compiler.js:1183:17

  • Hook.js:18 Hook.CALL_ASYNC_DELEGATE [as _callAsync]
    [posthtml-loader-require-bug]/[tapable]/lib/Hook.js:18:14

  • Compiler.js:1179
    [posthtml-loader-require-bug]/[webpack]/lib/Compiler.js:1179:33

  • Compilation.js:2785 finalCallback
    [posthtml-loader-require-bug]/[webpack]/lib/Compilation.js:2785:11

  • Compilation.js:3090
    [posthtml-loader-require-bug]/[webpack]/lib/Compilation.js:3090:11

  • Hook.js:18 Hook.CALL_ASYNC_DELEGATE [as _callAsync]
    [posthtml-loader-require-bug]/[tapable]/lib/Hook.js:18:14

1 ERROR in child compilations (Use 'stats.children: true' resp. '--stats-children' for more details)
webpack 5.69.0 compiled with 3 errors in 1679 ms

♻️ Reproduction (Code)

git clone https://github.com/azan-n/posthtml-loader-require-bug

🌐 Environment

html-loader: "^3.1.0"
posthtml: "^0.15.2"
webpack: "^5.69.0"
webpack-cli: "^4.9.2"

OS node npm/yarn package
[Ubuntu 20.04.3 LTS] [v16.13.0] [8.1.4] [^2.0.1]

Make posthtml a peer dependency?

This is the way that babel-loader does it. postcss-loader on the other hand bundles it directly.

The advantages are that the user has control over the posthtml version and the two are not so tightly bundled together. It also means that this package doesn't need to be re-released if there is a major version bump that doesn't break the api utilized by this loader. The disadvantage is that the user will need to run npm i posthtml posthtml-loader instead of just npm i posthtml-loader. Just looking at this now it seems to me like the advantages outweigh the disadvantages, but I could be convinced otherwise!

Is there a good way of injecting variables into HTML?

I really like the idea of breaking HTML out to be parsed and rendered by a javascript tool, so Kudos. I am wondering if one could integrate variables using posthtml in the loader though? Does this seem like a possibility. To give context what I am thinking of doing is to load an MJML template but to have {{}} syntax for the expression loader to enable personalized templates per users and would love to pass that in using the require() statement. I am trying to get my head around webpack and sometimes find myself confused so if there is anything you can suggest please assist.

Jade filename issue

Ok so this is a strange issue, and I'm not entirely sure how to go about solving it honestly, but will try to clearly explain it and see what you guys think.

I'm using posthtml with the jade plugin through this loader in webpack. My jade template uses an include, which the jade parser attempt to read in order to make it work. However jade it requires you to pass a filename option for each file so that it is able to resolve the path to any includes and read them correctly.

When using this loader, you configure it once upfront, and each file is loaded in by webpack, so there in no way to set the filename option accurately. Therefore it fails whenever you need to use an extend, include, etc.

I'm filing this here instead of in posthtml-jade because that plugin isn't the issue, it accept the filename option just fine if you pass it in. The issue is that there needs to be some way to pass the filename on a per-file basis as files are pushed through the posthtml-loader.

I took a quick look at the code for each of these libraries and it seems like this is not going to be simple. Any thoughts on how we could potentially resolve this?

template option

How to use it with posthtml-expressions?

import tpl from './tpl.html';

document.querySelector('#ex').innerHTML = tpl({ array: ['foo', 'bar'] });
<each loop="item, index in array">
  <p>{{ index }}. {{ item }}</p>
</each>

There are no tests?

Do you want me to add some tests? I'd be happy to, I think it would be a pretty nice benefit for this module...

Module not found: Error: Can't resolve 'posthtml-loader' in '<absolute path>'

After installing [email protected] I started getting errors that make my webpack build fail.

📝 Details

Module not found: Error: Can't resolve 'posthtml-loader' in ''

OS node npm/yarn package
macOS 10.13.1 8.9.1 npm 5.5.1 1.0.0

Installed [email protected] has main field in package.json set to index.js which doesn't exist.
Versions <1 had explicit main. Version 1.0.0 only has files which doesn't seem to be enough for webpack.

Adding "main": "lib" resolves the issue

No changes after live reloading

On edit any .html, there is no changes after live reloading is happens.
browser console output:

[webpack-dev-server] App updated. Recompiling...
index.js:551 [webpack-dev-server] App hot update...
log.js:24 [HMR] Checking for updates on the server...
log.js:24 [HMR] Nothing hot updated.
log.js:24 [HMR] App is up to date.

refactor tests

remove when, add tests for posthtml-load-config && webpack v2.0.0

migrate to `webpack-contrib` org and be official

Sorry for removing the issue template.

We want to provide official support for posthtml in webpack. If you have any questions do not hesitate to ask them. Recently we have given official support for many tools - like postcss, stylus, cssnano and etc. This eliminated many problems and wrong architectural decisions.

Same request for pug - pugjs/pug-loader#124 (comment)

add result.messages

posthtml(plugins).process(html, options).then((result) => {
   result.messages.forEach((msg) => {
     if (msg.type === 'warning') loader.emitWarning(msg.warning)
     if (msg.type === 'dependency') loader.addDependency(msg.file)
   })
})

ES5

Would you mind to merge a pull request with downgrade to ES5 to make this module compatible with older node.js versions?

How to make posthtml-loader and posthtml-include work with webpack-dev-server?

I run webpack-dev-server with these setting, like in documentation, and my includes tags in index.html not parse. But if I run "npm run build" with 'file-loader' instead 'html-loader', it works.

module: {
   rules: [
     {
       test: /\.html$/,
       use: [
         'html-loader',
         {
           loader: 'posthtml-loader',
           options: {
             plugins: [
               require('posthtml-include')()
             ]
           }
         }
       ]
     }
   ]
 }

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.