Giter Club home page Giter Club logo

rollup-plugin-pug's Introduction

rollup-plugin-pug

License npm Version Linux build Status Windows build status

Rollup plugin that transforms Pug v2 templates to ES6 modules.

  • Dynamic generation of HTML. Static HTML is optional and configurable.
  • Automatic import of the pug-runtime in your bundle, if required.
  • Automatic import of template extends and includes.
  • Source map support.
  • Support for ES6 import statements (moved out of the template).
  • Typescript v3.x definitions.

IMPORTANT

v1.1 requires Rollup 0.61 and node.js 6 or later, for previous versions use rollup-plugin-pug 0.1.6

Installation

npm install rollup-plugin-pug --save-dev

Usage

Create the template

//- template.pug
p= message

and import it as any other function:

import templateFn from './template.pug';

const context = { message: 'Hello World' };

console.log(templateFn(context));  // <p>Hello World</p>

or rename it for static compilation and import it as string:

import htmlString from './template.static.pug';

console.log(htmlString);  // <p>Hello World</p>

Build with something like...

import { rollup } from 'rollup';
import pug from 'rollup-plugin-pug';

rollup({
  entry: 'src/main.js',
  plugins: [
    pug({
      locals: { message: 'Hello World' }
    })
  ]
}).then(...)

That's it.

Options

In addition to the regular pug options, the plugin defines these:

  • staticPattern - Regex for files to compile and evaluate at build time to export plain HTML.
  • locals - Plain JavaScript object with values passed to the compiler for static compilation (Deprecated).
  • include - minimatch or array of minimatch with files that should be included by default.
  • exclude - minimatch or array of minimatch with files that should be excluded by default.
  • extensions - Array of extensions to process (don't use wildcards here).
  • pugRuntime - Custom Pug runtime filename (See note).
  • sourceMap - Enabled by default.

TIP: Use staticPattern: /\S/ to evaluate all the templates at build time.

Be carefull

The parameter passed to the static templates is a shallow copy of the plugin options. Do not change it unless you know what you doing.

When a template matches the staticPattern regex, the template is executed at complie-time and you load the resulting string through import at runtime, so it will not have access to runtime variables or methods. Instead, the plugin passes its options to the template at compile-time.

Default Options

The plugin has preset the following options:

{
  doctype: 'html',
  basedir: absolute(input),       // absolute path of the rollup `input` option
  compileDebug: false,            // `true` is recommended for development
  sourceMap: true,                // with or without compileDebug option
  inlineRuntimeFunctions: false,  // use the pug runtime
  extensions: ['.pug', '.jade'],
  staticPattern: /\.static\.(?:pug|jade)$/
}

See the full list and explanation in the API Documentation of the pug site.

Note: The default of staticPattern was defined to be compatibile with the old Jade plugin and so it has remained, but I prefer /\.html\.pug$/.

Custom runtime

The pugRuntime option can be set to false to avoid importing the runtime, but you must provide an equivalent pug object accessible to the template:

Disable the predefined runtime in rollup.config.js

  ...
  plugins: [
    pug({ pugRuntime: false })
  ]

and import the yours in your .pug files

- import pug from 'my-runtime'
p= name
//- ...etc

but the recommended option is name it in the config:

  // in rollup.config.js
   ...
   plugins: [
     pug({ pugRuntime: 'my-runtime' })
   ]

Search for "pugRuntime" in the test/run.js file to see examples.

What's New

v1.1.1

  • #14: fix (this.warn is not a function) - thanks to @leptonix

See the CHANGELOG for more changes.

Support my Work

I'm a full-stack developer with more than 20 year of experience and I try to share most of my work for free and help others, but this takes a significant amount of time and effort so, if you like my work, please consider...

Of course, feedback, PRs, and stars are also welcome ๐Ÿ™ƒ

Thanks for your support!

rollup-plugin-pug's People

Contributors

amarcruz avatar arxpoetica avatar leptonix avatar streetstrider 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

Watchers

 avatar  avatar  avatar

rollup-plugin-pug's Issues

Includes are not to be watched

If you use this plugin with rollup-watch (I don't know if it's related to this plugin or rollup-watch) the files you include are not to be watched. For example if you have:

// main.pug
include ./mixins

+mixin(name)
// mixins.pug

mixin mixin(name)
  div= name

and if you change mixins.pug the watch process does not reflect. Can you please look into that and tell if I should report the issue there (rollup-watch) or it's related to rollup-plugin-pug?

Generate an HTML file from result

rollup-plugin-postcss has an option for extracting the result into a CSS file by specifying extract: true.

Does rollup-plugin-pug has a similar option like the above? Because it'll be super helpful for bundling html files.

Error on install

It seems the installation is broken since last update (0.1.5). Everything works fine with 0.1.4.

Here is the error I receive.

[email protected] postinstall /Users/quentinroy/Workspace/test/node_modules/rollup-plugin-pug
node ./build-rt.js

module.js:487
throw err;
^

Error: Cannot find module '/Users/quentinroy/Workspace/test/node_modules/rollup-plugin-pug/build-rt.js'
at Function.Module._resolveFilename (module.js:485:15)
at Function.Module._load (module.js:437:25)
at Function.Module.runMain (module.js:605:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:575:3

I am using macOS Sierra, npm 5 and node 8.

plugin does not pass options as locals, but Pug itself does

Hello.
I got pretty simple config I'm using for pug templates:

{
	pretty: false,
	dev: false, // true or false
	basedir: 'path/here',
}

Pug pass dev property to all templates as local (and other two options as well). I expect rollup-plugin-pug to mimic this behavior when passing options to it. This isn't working as I expected, so if I would depend on dev in my templates I will got different rendering of template when using it directly via Pug renderer or via rollup plugin.

Update to Pug v3.0.0

Pug is long out of date. Should we also consider making Pug a peer dependency rather than a required dependency?

Unable to load pug-runtime

I'm attempting to use this plugin, but receive this error when I try to compile:

[!] Error: Could not load pug-runtime (imported by /home/gabe/Coding/notify/src/dom/pug/message-container.pug): The argument 'path' must be a string or Uint8Array without null bytes. Received '\u0000pug-runtime'

Here's the gist of my code, for reference:

// rollup.config.js
import pug from 'rollup-plugin-pug';

export default {
  plugins: [
    pug()
  }
};
// somefile.pug
div(class='my-class')
// index.js
import somefile from './somefile.pug';

I'm not passing any parameters into the pug plugin, and so I'm not sure what's going wrong.

Full pug support

Will this plugin fully support pug syntax like mixins, for example?

Importing modules

How does one import modules?

- import 'something';
p= something('something')

errors out with:
Error: 'import' and 'export' may only appear at the top level (2:0)

Broken sourcemap

My error message was
Plugins that transform code (such as 'rollup-plugin-pug') should generate accompanying sourcemaps

In my main.js

import html from '../pug/template.pug';

In my rollup.config.js

import pug from 'rollup-plugin-pug';

export default {
	input: 'src/js/main.js',
	output: {
		file: 'dist/js/main.js',
		format: 'iife',
		sourcemap: 'inline',
	},
	plugins: [
		pug({
			include: 'src/pug/**.pug',
			pretty: true,
			staticPattern: /\S/,
			sourceMap: true
		})
	]
}

Upgrade rollup version

rollup-plugin-pug currently only supports rollup v0.4.3. The recent rollup release actually changed the options entry and src to input and output. This is causing failed test cases if we run rollup-plugin-pug with latest rollup version (v0.6.5). entry and src will also be deprecated soon.

Some ideas for improvemnent

Hi, there - great work!

I have tried this plugin and would like to suggest some ideas for improvement:

  1. You have runtime as CJS - i am suggesting to convert this to modules
  2. You check if need to add runtime by regexp searching (i know it is best possible way now - because of pug code gen module). I suggest there to use regexp to replace pug.method names while collecting them for es6 import.
    You can generate regexp something like Object.keys(require('pug-runtime')).map(m => 'pug\\.'+m).join('|'), so while doing string.replacing you can guther all used methods and include in moduels import only in use.

What do you think? I can create PR if you do not have time.

ESLint configuration may be out of date

I'm getting a console error for the config (below)

Perhaps the ESLint config has changed since this was implemented?

Error log:

[!] (plugin eslint) Error: ESLint configuration in node_modules\rollup-plugin-pug\.eslintrc.js is invalid:
        - Property "overrides" is the wrong type (expected array but got `{"files":["test/*.js"],"env":{"mocha":true},"rules":{"no-console":0}}`).

node_modules\rollup-plugin-pug\dist\runtime.es.js
Error: ESLint configuration in node_modules\rollup-plugin-pug\.eslintrc.js is invalid:
        - Property "overrides" is the wrong type (expected array but got `{"files":["test/*.js"],"env":{"mocha":true},"rules":{"no-console":0}}`).

    at validateConfigSchema (myproject\node_modules\rollup-plugin-eslint\node_modules\eslint\lib\shared\config-validator.js:286:15)
    at ConfigArrayFactory._normalizeConfigData (myproject\node_modules\rollup-plugin-eslint\node_modules\eslint\lib\cli-engine\config-array-factory.js:574:9)
    at ConfigArrayFactory._loadConfigDataInDirectory (myproject\node_modules\rollup-plugin-eslint\node_modules\eslint\lib\cli-engine\config-array-factory.js:526:33)
    at ConfigArrayFactory.loadInDirectory (myproject\node_modules\rollup-plugin-eslint\node_modules\eslint\lib\cli-engine\config-array-factory.js:434:18)
    at CascadingConfigArrayFactory._loadConfigInAncestors (myproject\node_modules\rollup-plugin-eslint\node_modules\eslint\lib\cli-engine\cascading-config-array-factory.js:328:46)
    at CascadingConfigArrayFactory._loadConfigInAncestors (myproject\node_modules\rollup-plugin-eslint\node_modules\eslint\lib\cli-engine\cascading-config-array-factory.js:347:20)
    at CascadingConfigArrayFactory.getConfigArrayForFile (myproject\node_modules\rollup-plugin-eslint\node_modules\eslint\lib\cli-engine\cascading-config-array-factory.js:272:18)
    at CLIEngine.isPathIgnored (myproject\node_modules\rollup-plugin-eslint\node_modules\eslint\lib\cli-engine\cli-engine.js:951:18)
    at Object.transform (myproject\node_modules\rollup-plugin-eslint\index.js:36:15)
    at C:\Users\paulb\AppData\Roaming\npm\node_modules\rollup\dist\shared\node-entry.js:13113:25

Keeping pug-runtime as external

Currently, whatever is registered in rollup.config.js, pug-runtime is embedded in the compiled file.
Is there any way not to bundle it with the library and keep it as an external?

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.