Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
@webdiscus/pug-loader
Advanced tools
The pug loader resolves paths and webpack aliases in a pug template and compiles it to HTML or into a template function.
This pug-loader render pug templates into HTML to save it in a file or compile pug to template function for usage the pug directly in JavaScript.
The pug loader can resolve paths and webpack aliases for extends
include
require()
.
NEW: The
pug-loader
is now the part of the pug-plugin. This plugin extracts HTML from thepug
files defined in the webpack entry and save them in the output directory. Now is possible definepug
files directly inwebpack entry
. See usage examples.
compile
render
html
asset/resource
asset/inline
asset/source
asset
file-loader
url-loader
raw-loader
.pug-walk
package. Working with Pug < v3.0.2 is not guaranteed.HTML string
to save it as static HTML filetemplate function
for usage in JavaScriptCommonJS
or ESM
syntaxresolve.alias
and resolve.plugins
tsconfig.json
using tsconfig-paths-webpack-plugin
srcset
of img
tag~
@
for webpack resolve.alias
Angular Component
pugjs/pug-loader
pugjs/pug-loader
To extract HTML from a pug template and save it to a file, use the pug-plugin or html-webpack-plugin.
pug-plugin
Install the pug-plugin
if you want extract HTML from pug defined in webpack entry.
npm install pug-plugin --save-dev
Note: the
pug-plugin
already contain thepug-loader
, not need to install extra anypug-loader
.
Change your webpack.config.js according to the following minimal configuration:
const path = require('path');
const PugPlugin = require('pug-plugin');
module.exports = {
output: {
path: path.join(__dirname, 'public/'),
publicPath: '/', // must be defined any path, `auto` is not supported yet
},
entry: {
index: './src/index.pug', // the `pug-plugin` extract HTML from entry file
},
plugins: [
new PugPlugin(), // add it to handle pug files in entry
],
module: {
rules: [
{
test: /\.pug$/,
loader: PugPlugin.loader, // the pug-plugin already contain this pug-loader
},
],
},
};
html-webpack-plugin
Install the pug-loader
only if you use the html-webpack-plugin
.
npm install @webdiscus/pug-loader --save-dev
Change your webpack.config.js according to the following minimal configuration:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
output: {
path: path.join(__dirname, 'public/'),
publicPath: '/', // must be defined any path, `auto` is not supported yet
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'src/index.pug'),
filename: 'index.html',
}),
],
module: {
rules: [
{
test: /\.pug$/,
loader: '@webdiscus/pug-loader',
},
],
},
};
Install the pug-loader
.
npm install @webdiscus/pug-loader --save-dev
Change your webpack.config.js according to the following minimal configuration:
const path = require('path');
module.exports = {
output: {
path: path.join(__dirname, 'public/'),
publicPath: '/', // must be defined any path, `auto` is not supported yet
},
entry: {
index: './src/index.js', // load a pug file in JS
},
module: {
rules: [
{
test: /\.pug$/,
loader: '@webdiscus/pug-loader',
},
],
},
};
Load a pug template in JavaScript. Optional you can pass any data into generated template function.
./src/index.js
const tmpl = require('template.pug');
const html = tmpl({
myVar: 'value',
});
See original description of options
basedir
Type: string
Default: /
The root directory of all absolute inclusion.
doctype
Type: string
Default: html
Specifies the type of document. See available doctypes.
self
Type: boolean
Default: false
Use the self
as namespace for the local variables in template. It will speed up the compilation, but for access to variable, e.g. myVariable
, you must write self.myVariable
.
globals
Type: Array<string>
Default: []
Add a list of global names to make accessible in templates.
filters
Type: object
Default: undefined
Hash table of custom filters.
Filters let to use other languages in Pug templates.
plugins
Type: Array<Object>
Default: []
Plugins allow to manipulate pug tags, template content in compile process.
How it works see in source of pug.
compileDebug
Type: boolean
Default: false
Includes the function source in the compiled template to improve error reporting.
pretty
Type: boolean
Default: false
This option is deprecated by pugjs and always is false
. Don't use it.
method
Type: string
Default: compile
Values:
compile
the pug template compiles into a template function and in JavaScript can be called with variables to render into HTML at runtime. ?pug-compile
. Can be used if the method is render
. render
the pug template renders into HTML at compile time and exported as a string.
All required resource will be processed by the webpack and separately included as added strings wrapped to a function. ?pug-render
. Can be used if the method is compile
or is not defined in options. html
the template renders into a pure HTML string at compile time. The method need an addition loader to handles the HTML. html-loader
see usageEmbedded resources such as
img(src=require('./image.jpeg'))
handles at compile time by the webpack using asset/resource.
esModule
Type: Boolean
Default: false
Enable / disable ESM syntax in generated JS modules.
Values:
true
The pug-loader
generates JS modules with the ESM syntax. import html from 'template.pug';
. false
defaults. The pug-loader
generates JS modules with the CommonJS modules syntax. const html = require('template.pug')
. false
for compatibility with the JS modules that is generated by the original pug-loader.Note: The option
esModule
is irrelevant for thehtml
method, because it returns a pure HTML string.
For generates smaller and faster JS code, it is recommended to use this options:
{ method: 'render', esModule: true }
data
Type: Object
Default: {}
The custom data will be passed in all pug templates, it can be useful by pass global data.
compile
(default)In JavaScript the required template will be compiled into template function.
In webpack config add to module.rules
:
{
test: /\.pug$/,
loader: '@webdiscus/pug-loader',
options: {
method: 'compile' // default method `compile` can be omitted
}
}
In JavaScript, the result of require () is a template function. Call the template function with some variables to render it то HTML.
const tmpl = require('template.pug');
const html = tmpl({ key: 'value' }); // the HTML string
To render the pug direct into HTML, use the query parameter ?pug-render
.
// compile into template function, because loader option 'method' defaults is 'compile'
const tmpl = require('template.pug');
const html = tmpl({ key: 'value' });
// render the pug file into HTML, using the parameter 'pug-render'
const html2 = require('template2.pug?pug-render');
Note: if the query parameter
pug-render
is set, then will be used rendering for this template, independent of the loader optionmethod
. Variables passed in template with methodrender
will be used at compile time.
render
This method will render the pug into HTML at compile time.
In webpack config add to module.rules
:
{
test: /\.pug$/,
loader: '@webdiscus/pug-loader',
options: {
method: 'render'
}
}
In JavaScript the result of require() is an HTML string.
const html = require('template.pug'); // the HTML string
To generate a template function for passing the data in pug at realtime, use the query parameter ?pug-compile
.
// render into HTML, because loader option 'method' is 'render'
const html = require('template.pug');
// compile into template function, using the parameter 'pug-compile'
const tmpl2 = require('template2.pug?pug-compile');
const html2 = tmpl2({...});
html
This method will render the pug to pure HTML and should be used with an additional loader to handle HTML.
In webpack config add to module.rules
:
{
test: /\.pug$/,
use: [
{
loader: 'html-loader',
options: {
esModule: false, // allow to use the require() for load a templqte in JavaScript
},
},
{
loader: '@webdiscus/pug-loader',
options: {
method: 'html',
},
},
],
}
In JavaScript the result of require() is an HTML string:
const html = require('template.pug'); // the HTML string
By default, the pug file is compiled as template function, into which can be passed an object with template variables.
const tmpl = require('template.pug');
const html = tmpl({
myVar: 'value',
foo: 'bar'
});
But how pass variables in template which is rendered into HTML?
Variables can be passed with query parameters.
const html = require('template.pug?myVar=value&foo=bar');
or as a JSON object:
const html = require('template.pug?' + JSON.stringify({ myVar: 'value', foo: 'bar' }));
Use variables myVar
and foo
in pug template.
div The value of "myVar": #{myVar}
div The value of "foo": #{foo}
Usage of query parameters is legal and official documented feature of webpack loader.
Pass myData
object via query.
entry: {
about: './src/pages/about.pug?myData=' + JSON.stringify({ title: 'About', options: { uuid: 'abc123' } })
}
Use the object myData
in pug template.
html
head
title= myData.title
body
div UUID: #{myData.options.uuid}
To pass global data to all pug templates, add the loader options data
with any object.
module.exports = {
module: {
rules: [
{
test: /\.pug$/,
loader: '@webdiscus/pug-loader',
options: {
data: { "lang": "en-EN" }
}
},
],
},
};
Use the variable lang
in pug.
html(lang=lang)
head
body
The user data can be passed into pug template with two ways:
module.exports = {
plugins: [
new HtmlWebpackPlugin({
title: 'The some page', // avaliable in pug as `htmlWebpackPlugin.options.title`
template: path.join(__dirname, 'src/index.pug?' + JSON.stringify({ myVar: 'value' })), // avaliable as `myVar`
filename: 'index.html',
}),
],
module: {
rules: [
{
test: /\.pug$/,
loader: '@webdiscus/pug-loader',
},
],
},
};
Use the passed variables htmlWebpackPlugin.options
and myVar
in pug template:
html
head
title= htmlWebpackPlugin.options.title
body
div= myVar
You can load data directly in pug.
data.json
[
{ "id": 1, "name": "abc" },
{ "id": 2, "name": "xyz" }
]
Require the JSON file in pug.
- var myData = require('./data.json')
each item in myData
div #{item.id} #{item.name}
For processing image resources in templates with webpack use the require()
function:
img(src=require('./path/to/image.jpeg'))
To handles embedded resources in pug add the webpack module asset/resource
:
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|jpeg)/,
type: 'asset/resource',
generator: {
filename: 'assets/images/[name].[hash:8][ext]',
},
},
]
},
};
More information about asset-modules see here.
The example of dynamically generating embedded resources in template:
- files = ['image1.jpeg', 'image2.jpeg', 'image3.jpeg']
each file in files
img(src=require(file))
The example of webpack alias used in the table below:
resolve: {
alias: {
Images: path.join(__dirname, 'src/images/'),
},
}
Code | @webdiscus/ pug-loader | pugjs/ pug-loader |
---|---|---|
img(src=require('image.jpeg')) | OK | fail |
img(src=require('./image.jpeg')) | OK | OK |
img(src=require('../images/image.jpeg')) | OK | OK |
img(src=require('Images/image.jpeg')) | OK | OK |
- var file = 'image.jpeg' img(src=require(`Images/${file}`)) | OK | OK |
- var file = './image.jpeg' img(src=require(file)) | OK | fail |
- var file = 'images/image.jpeg' img(src=require(file)) | OK | fail |
- var file = '../images/image.jpeg' img(src=require(file)) | OK | fail |
- var file = 'image.jpeg' img(src=require(`./images/${file}`)) | OK | OK |
- var file = 'image.jpeg' img(src=require('../images/' + file)) | OK | OK |
the pugjs/pug-loader can't resolve when used a mixin and require on same file: include mixins img(src=require('./image.jpeg')) | OK | fail |
Install
npm i --saveDev @webdiscus/pug-loader pug-plugin-ng
in pug-loader can be used optional a plugin, e.g. pug-plugin-ng, to allow unquoted syntax of Angular: [(bananabox)]="val"
Create the file webpack.config.js
in root directory of angular project:
module.exports = {
module: {
rules: [
{
test: /\.pug$/,
loader: '@webdiscus/pug-loader',
options: {
method: 'render',
doctype: 'html',
plugins: [require('pug-plugin-ng')],
},
},
],
},
};
Bind the file webpack.config.js
in the Angular config angular.json
:
{
// ...
"projects": {
// ...
"architect": {
"build": {
// replace architect.build.builder with this value:
"builder": "@angular-builders/custom-webpack:browser",
// add the options:
"options": {
"aot": true,
"customWebpackConfig": {
"path": "./webpack.config.js" // the path to webpack.config.js
},
// ...
},
// ...
},
"serve": {
// replace architect.serve.builder with this value:
"builder": "@angular-builders/custom-webpack:dev-server",
"options": {
"browserTarget": "<app-name>:build"
},
// ...
},
// ...
}
}
},
}
In a component file, e.g. ./src/app/app.component.ts
set the templateUrl
with pug file:
import { Component } from '@angular/core';
// the variable `description` will be passed into pug template via resource query
const templateVars = '{"description": "Use pug template with Angular."}';
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
templateUrl: './app.component.pug?' + templateVars,
})
export class AppComponent {
title = 'ng-app';
}
Create a pug template, e.g. ./src/app/app.component.pug
:
h1 Hello Pug!
p Description: #{description}
See the complete source of the example.
srcset
in img
tagimg(srcset=`${require('./image1.jpeg')} 320w, ${require('./image2.jpeg')} 640w` src=require('./image.jpeg'))
output
<img srcset="/assets/image1.f78b30f4.jpeg 320w, /assets/image2.f78b30f4.jpeg 640w" src="/assets/image.f78b30f4.jpeg">
Use the require()
for CommonJS files in pug templates.
The JS module say-hello.js
module.exports = function (name) {
return `Hello ${name}!`;
}
Use the module sayHello
in pug template.
- var sayHello = require('./say-hello')
h1 #{sayHello('pug')}
npm run test
will run the unit and integration tests.
npm run test:coverage
will run the tests with coverage.
ansis
- color styling for ANSI terminalspug GitHub
pug API Reference
pug-plugin
1.6.4 (2022-01-31)
htmlWebpackPlugin.options
in pug template, #8FAQs
Pug loader renders Pug files into HTML or compiles them into a template function.
The npm package @webdiscus/pug-loader receives a total of 1,329 weekly downloads. As such, @webdiscus/pug-loader popularity was classified as popular.
We found that @webdiscus/pug-loader demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.