Security News
How Threat Actors are Abusing GitHub’s File Upload Feature to Host Malware
GitHub is susceptible to a CDN flaw that allows attackers to host malware on any public repository.
html-in-js
Advanced tools
Readme
Programming a simple, static, website is trickier than it looks. The first version is usually quick and easy to write but every subsequent version gets harder and more brittle with each change.
The lessons we have learnt in programming - localise scope, reuse components, calculate values from data - all hit a brick wall when coding a raw websites.
The problem is that HTML/CSS is not a 'real' programming language and it is a struggle to get it to behave properly. In response to this problem the programming community quickly moved on from using raw HTML/CSS and created new ways of generating them instead.
We call these 'templates' and the way most of them work is to create a new language structure that is some mix of HTML and supporting programming structures - loops, conditionals and so on.
Now these have been excellent solutions and have taken us far yet they all still suffer from two fundamental problems:
So The Perfect Site Generator would - ideally - require
And - with the advent of ES6 - this Magical Perfect Site Generation Option is now a reality!
In ES6 Javascript now provides Template Strings as part of it’s core language. While it is easy to overlook this addition to the language as a “just prettier syntax” Template Strings are pretty powerful things.
What is a template string? Well they are like ‘normal’ javascript strings except that they can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}
). So we can change this string:
'hello there ' + name + '! Great to see you.'
to this
`hello there ${name}! Great to see you.`
The power here comes when we realize that the expression
is fully functional Javascript. That means we can call functions, include packages, do calculations, … - do everything we could do with the full power of Javascript behind us.
The best way to explain it's power is to provide examples and how-to’s so let’s do that next.
(or a quick look at some examples)
let index = `<!doctype html>
<html>
<head>
<title>${title}</title>
</head>
<body>
${content()}
</body>
</html>`
write('index.html', index)
...
let title = 'Welcome to HTML - in - JS'
...
function content() {
return `
<div class=container>
<div class='col col-4'
${sidebar()}
</div>
<div class='col col-8'>
${maincontent()}
</div>
</div>`
}
...
We can see how similar the content above looks like a “template language” but it’s just plain vanilla Javascript.
We all love markdown. It’s a wonderful way of writing text with just enough symbols thrown in to make it pleasing to write and useful to generate.
So how would we use markdown if we wanted in our site? Simple, just write our content in markdown in some file
# First Fig
My candle burns at both ends;
It will not last the night;
But ah, my foes, and oh, my friends --
It gives a lovely light!
*-- Edna St Vincent Millay*
Then use our favorite markdown package to parse it and give us the content we need:
function poem(file) {
return md.render(read(file))
}
This is a classic use case for templates - looping. But now, instead of having to learn a new syntax we use javascript directly.
`<ul>
${data.map(item => `<li>${item}</li>`).join('')}
</ul>`
When generating HTML-from-JS there are a few operations that are commonly required - reading from disk, saving a file, parsing markdown, using a HTML template, and so on.
Here we have some helper functions that support these common cases which can be used to quickstart your site development (or just as a starting point for anyone who is creating their own).
/* example use */
const helper = require('html-in-js')
function createSite() {
helper.save(helper.md(helper.read('content.md)), 'index.html')
...
}
This is the list of helper functions available:
Function | Description | Notes |
---|---|---|
read | Read data from file | read('content.md') |
lines | Split data into lines | lines(data) Splitting data into lines is useful for processing/filtering and so on |
save | Saves data into file | save(html, path) |
copy | Copies file into deployment | copy(src, dst) |
mkdir | Makes a directory path (recursively) | mkdir(path) |
exec | Executes a command in the default shell (only pass in trusted commands!) | exec(cmd) or exec([cmd,and,args]) : returns (err, {stdout,stderr,exitCode})
Takes an optional options argument that supports all spawn options. The most useful are { cwd: 'current/working/directory', env: {key:value}, quiet: true } . USE WITH CARE
|
md | Convert markdown into HTML | md('# Hello World!') |
htmlboilerplate | Use HTML 5 Boilerplate | htmlboilerplate() - returns the HTML boilerplate which can then be edited with lines() or edit() htmlboilerplate(location) - saves all required files (jquery, normalize.css,etc) into location (you can update the webmanifest/css/js and save your own favicon and icon.png) |
clean | Cleans/deletes the file/folder passed in | USE WITH CARE |
edit | Can be used to edit a file | edit(line => if(line.match(/sidebar content/)) return sidebar_content()) edit(line => if(line.match/jquery/) return helper.DELETE) |
findAll | Returns all files in a path recursively | findAll('assets','.js') findAll('assets,'js') // Also works findAll('assets') // Don't filter by extension |
You can see an example of HTML-in-JS in action here
The preceeding examples should have given you a feel for how simple and elegant it is to use HTML-in-JS.
I encourage anyone who believes in html-in-js to contribute more examples and how-to’s to spur ideas and drive html-in-js's adoption.
Thanks.
FAQs
Easily write modular and flexible HTML sites using just the javascript you know and love
The npm package html-in-js receives a total of 5 weekly downloads. As such, html-in-js popularity was classified as not popular.
We found that html-in-js 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.
Security News
GitHub is susceptible to a CDN flaw that allows attackers to host malware on any public repository.
Security News
At Node Congress, Socket CEO Feross Aboukhadijeh uncovers the darker aspects of open source, where applications that rely heavily on third-party dependencies can be exploited in supply chain attacks.
Research
Security News
The Socket Research team found this npm package includes code for collecting sensitive developer information, including your operating system username, Git username, and Git email.