Skip to content
This repository has been archived by the owner on Jan 12, 2022. It is now read-only.

Feat/add runtime script build #20

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions src/defaultConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,8 @@ export default {
'src/components/**/*.json',
'src/resources/**/*.json'
],
enableRuntimeBuild: false,
enableRuntimeBuildMinify: true,
runtimeBuildPath: 'resources/js/handlebars.templates.js',
runtimeBuildNamespace: 'biotope.configuration.data.tpl',
} as BuildPluginHbsConfig
23 changes: 23 additions & 0 deletions src/helpers/declare.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const toDefinitionChain = parts => parts.reduce((aggr, curr) => aggr + `["${curr}"]`, '');
const toDefinitiononWindow = (p, value?) => `window${p} = ${value || `window${p} || {};`}`;

const toDeclaration = (path, value?) => {
return path
.split('.')
.map((part, index, path) => path.slice(0,index+1))
.map(toDefinitionChain)
.map((chain, index, arr) => {
if(index === arr.length - 1) {
return toDefinitiononWindow(chain, value)
}
return toDefinitiononWindow(chain)
}).join('\n');
}

const declare = (path, options = {} as any) => {
const existing = toDeclaration(options.declared || '');
return toDeclaration(path, options.value).replace(existing, '')
}


export default declare;
10 changes: 7 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,18 @@ import { watch } from 'chokidar';
import * as merge from 'deepmerge';
import registerHelpers from "./registerHelpers";
import defaultConfig from './defaultConfig';
import createRuntimeScript from './runtime';
import { BuildPluginHbsConfig } from './typings/Config';


const createGlobPattern = (array: string[]) => array.length === 1 ? array[0] : `{${array.join(',')}}`;

const compileHbs = (filepath: string, data: any, hbs, config) => {
const content = fs.readFileSync(filepath, {encoding: 'utf8'});
const template = hbs.compile(content);
const targetPath = filepath.substr(filepath.indexOf('/components/') + 1);

fs.createFileSync(`${config.paths.distFolder}/${path.dirname(targetPath)}/${path.basename(targetPath, '.hbs')}.html`);
fs.writeFileSync(`${config.paths.distFolder}/${path.dirname(targetPath)}/${path.basename(targetPath, '.hbs')}.html`, template({data}));
fs.outputFileSync(`${config.paths.distFolder}/${path.dirname(targetPath)}/${path.basename(targetPath, '.hbs')}.html`, template({data}));
};

const gatherData = (globString: string): any => {
Expand All @@ -42,13 +43,16 @@ const registerPartials = (partialPattern: string, hbs) => {
export default (pluginOptions: Partial<BuildPluginHbsConfig> = {}) => {
const pluginConfig = merge(defaultConfig, pluginOptions);
return async (buildConfig, isServing) => {
if(pluginConfig.enableRuntimeBuild) {
createRuntimeScript(pluginConfig, handlebars, `${buildConfig.paths.distFolder}/${pluginConfig.runtimeBuildPath}`)
}
registerHelpers(handlebars);
const templateData = gatherData(createGlobPattern(pluginConfig.dataPatterns));
registerPartials(createGlobPattern(pluginConfig.partialPatterns), handlebars)

if(isServing) {
watch(createGlobPattern(pluginConfig.srcPatterns)).on('all', (err, filepath) => {
compileHbs(filepath, templateData, handlebars, buildConfig)
compileHbs(filepath, templateData, handlebars, buildConfig);
});
} else {
glob(createGlobPattern(pluginConfig.srcPatterns), (err, filepaths) => {
Expand Down
4 changes: 3 additions & 1 deletion src/registerHelpers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { bioDef } from "./helpers";
import * as merge from 'deepmerge';

const registerHelpers = (handlebars) => {
// Has to stay es5 as it is used as is in the browser

const registerHelpers = function(handlebars) {
handlebars.registerHelper('bioDef', bioDef);

/**
Expand Down
45 changes: 45 additions & 0 deletions src/runtime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import * as uglifyjs from '@node-minify/uglify-js';
import * as minify from '@node-minify/core';
import { BuildPluginHbsConfig } from './typings/Config';
import * as fs from 'fs-extra';
import * as glob from 'glob';
import * as path from 'path';
import declare from './helpers/declare';
import registerHelpers from "./registerHelpers";

const createGlobPattern = (array: string[]) => array.length === 1 ? array[0] : `{${array.join(',')}}`;

const precompileRuntimeTemplates = (templatePattern: string, hbs, namespace: string): string => {
const files = glob.sync(templatePattern);
const precompiled = files.map((filepath) => {
const content = fs.readFileSync(filepath, {encoding: 'utf8'});
return declare(`${namespace}.${path.basename(filepath).replace(path.extname(filepath), '')}`, {declared: namespace, value: `Handlebars.template(${hbs.precompile(content)})`});
});
return precompiled.join('');
}

const precompileRuntimePartials = (partialPattern: string, hbs): string => {
const files = glob.sync(partialPattern);
const precompiled = files.map((filepath) => {
const content = fs.readFileSync(filepath, {encoding: 'utf8'});
return `Handlebars.registerPartial('${path.basename(filepath, path.extname(filepath))}', Handlebars.template(${hbs.precompile(content)}));`;
});
return precompiled.join('');
}

const createRuntimeScript = (config: BuildPluginHbsConfig, hbs, targetPath: string) => {
const script = `(function (root, factory) {if (typeof module === \'object\' && module.exports) {module.exports = factory(require(\'handlebars\'));} else {factory(root.Handlebars);}}(this, function (Handlebars) { (${registerHelpers})(Handlebars);\n ${declare(config.runtimeBuildNamespace)}\n${precompileRuntimePartials(createGlobPattern(config.partialPatterns), hbs)}\n${precompileRuntimeTemplates(createGlobPattern(config.srcPatterns), hbs, config.runtimeBuildNamespace)} }));`
fs.outputFileSync(targetPath, script);
if(config.enableRuntimeBuildMinify) {
minify({
compressor: uglifyjs,
input: targetPath,
output: targetPath,
callback: function(err, min) {
console.error(err);
}
});
}
}

export default createRuntimeScript;
4 changes: 4 additions & 0 deletions src/typings/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,8 @@ export interface BuildPluginHbsConfig {
srcPatterns: string[];
partialPatterns: string[];
dataPatterns: string[];
enableRuntimeBuild: boolean;
enableRuntimeBuildMinify: boolean;
runtimeBuildPath: string;
runtimeBuildNamespace: string;
}
2 changes: 2 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
"lib": ["es6", "es7"],
"target": "es6",
"outDir": "dist",
"declaration": true,
"declarationDir": "dist",
"moduleResolution": "node",
"module": "commonjs",
"typeRoots": [
Expand Down