Skip to content

Instantly share code, notes, and snippets.

@newbornfrontender
Created June 4, 2020 07:35
Show Gist options
  • Save newbornfrontender/8f6ee65716789c40c2b4e7699d4693a9 to your computer and use it in GitHub Desktop.
Save newbornfrontender/8f6ee65716789c40c2b4e7699d4693a9 to your computer and use it in GitHub Desktop.
rollup-html
import fs from 'fs/promises';
import path from 'path';
import htmlnano from 'htmlnano';
import html from '@rollup/plugin-html';
const env = process.env.NODE_ENV;
const isProd = env === 'production';
const template = async ({ attributes, files, title }) => {
const code = await fs.readFile(
path.resolve(__dirname, 'src/index.html'),
'utf8',
);
const baseTemplate = `
<!doctype html>
<html lang="${attributes.html.lang}" dir="${attributes.html.dir}">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>${title}</title>
<link rel="preload" href="index.css" as="style" />
${files.js.map(
({ fileName }) => `<link rel="modulepreload" href="${fileName}"/>`,
)}
<link rel="stylesheet" href="index.css" />
</head>
<body>
${code}
${files.js.map(
({ fileName }) =>
`<script type="${attributes.script.type}" src="${fileName}"></script>`,
)}
</body>
</html>
`;
if (isProd) {
const { html: minifiedTemplate } = await htmlnano.process(baseTemplate);
return minifiedTemplate;
}
return baseTemplate;
};
export default (args) =>
html({
template,
attributes: {
html: {
dir: 'ltr',
lang: 'en',
},
},
...args,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment