StaticBuild

The StaticBuild class can be used in a gulp, grunt or other JS build pipeline to assist with paths, versioning, i18n and bundling. Fields marked with `@configurable` are able to be loaded from the JSON configuration file specified in the constructor.

Constructor

 

StaticBuild(pathOrOpt, opt)

Creates a new StaticBuild with the given path and/or options. If no path is supplied, the default file path of './staticbuild.json' is used.

ArgumentTypeDescription
pathOrOptstring,objectPath string or options object.
optobjectOptions object.
opt.pathstringPath to a configuration file.
opt.bundlingbooleanTrue if bundling is active.
opt.devbooleanTrue if dev mode is active.
opt.verbosestring,numberTrue to or a positive number to enable verbose logging.
opt.restartbooleanTrue to enable restarting dev mode.
opt.restartDelaynumberMillisecond delay before restart.

Constructor examples

// Construct with a configuration file...
var build = new StaticBuild('./staticbuild.json');

// with the default file ('./staticbuild.json')...
var build = new StaticBuild();

// with a configuration file and other options...
var build = new StaticBuild('./staticbuild.json', {
  verbose: true
});

// or with options containing a configuration file path...
var build = new StaticBuild({
  path: './staticbuild.json',
  verbose: true
});

Fields

 

autoContext@configurableboolean

True if a view context should be created automatically.

Default valuetrue

 

autoMinSrc boolean

True if pre-minified sources should be located by default.

 

baseDir string

Path to the directory containing the build config file.

 

bundle@configurable

Collection of bundles.

 

bundlePath@configurablestring

Relative path where bundled files should be placed by default.

Default value/lib/$(bundle)

 

bundling@configurableboolean

True if the bundle should be rendered instead of the source paths.

 

context 

The view context.

 

contextBuildVar@configurablestring

Name of the variable to expose StaticBuild in the view context.

Default valuebuild

 

contextFile@configurablestring

Path to a separate file containing the view context.

 

defaultEngineName@configurablestring

Name of the default view engine.

Default valuejade

 

defaultLocale@configurablestring

Id of the default locale.

Default valueen

 

defaultView@configurablestring

Name of the default view file (without file extension).

Default valueindex

 

destDir@configurablestring

Path to the destination directory.

Default valuedist

 

dev boolean

True if dev mode is active.

 

devServer@configurable

The dev server configuration.

ConfigurationThe `host` and `port` properties may be configured.

 

engine@configurable

Contains view engine configurations.

ConfigurationThe jade, less, nunjucks and sass engines are all configurable here.

 

errors Array.<string>

Array of errors or error messages.

 

favicon@configurablestring

Path to a favicon.

Default valuefavicon.ico

 

fileName string

Name of the build config file.

 

filePath string

Path to the build config file (includes fileName).

 

i18n 

The i18n module used to provide translate and other functions.

 

ignore Array.<string>

Globs of file paths to ignore.

 

info Array.<string>

Array of information messages.

 

locale string

Id of the current locale.

 

locales@configurableArray.<string>

Array of available locale ids.

 

localesConfigured boolean

True if locales have been supplied from the config file.

 

localesDir@configurablestring

Path to the locales directory containing translations.

Default valuelocales

 

packageFile@configurablestring

Path to the package file.

Default valuepackage.json

 

pathMap@configurable

Contains paths that are mapped to the source directory.

Default value
{}

 

pathTokens@configurable

Sets of tokens for replacing different items in file or url paths.

Default value
{"bundleName":"","bundleVer":"","bundlePath":"","packageVersionDefault":"","packageVersionHashid":"","packageVersionNumber":""}
ConfigurationItems from the configuration file are merged into the default set.

 

pkg 

Data from package.json

 

pkgVer string

Package Version

 

pkgVerHash string

Package Version Hashid

 

proxyMap@configurable

Contains url paths to map via an http proxy.

Default value
{}

 

sourceDir@configurablestring

Path to the source directory.

Default valuesrc

 

usePkgVerHashDefault@configurableboolean

True if pkgVerHash should be used when replacing pathTokens.packageVersionDefault.

Default valuetrue

 

verbose@configurableboolean,number

True or a Number to set the verbosity level.

ConfigurationCan only be set to true or a positive integer from a configuration file.

 

versionHash@configurable

Configuration for hashing version strings.

ConfigurationThe `salt`, `alphabet` and `minLength` fields are configurable.

 

versionHashIds 

Cache of hashed version strings.

 

versionHasher 

An instance of hashids or compatible: `{String encode(Number)}`.

 

warnings Array.<string>

Array of warning messages.

Methods

 

appendFilename(pathStr, valueToAppend)string

Returns the pathStr after appending the given value to the fileName, before the extension.

ArgumentTypeDescription
pathStrstringThe file path.
valueToAppendstringThe value to append.
ReturnsstringThe pathStr with value appended.

 

appendFilenamePart(pathStr, valueToAppend)string

Returns the pathStr with the given part appended to the fileName, before the extension, using a standard dash as a delimiter.

ArgumentTypeDescription
pathStrstringThe file path.
valueToAppendstringThe value to append.
ReturnsstringThe pathStr with value appended.

 

bundledCss(name, resultPath)

Stores the result path for the bundled css, for rendering later.

ArgumentTypeDescription
namestringName of the bundle.
resultPathstringPath to the bundled file.

 

bundledCssInStream(name, logger)stream.Transform

Stores the result path for the bundled css, for rendering later.

ArgumentTypeDescription
namestringName of the bundle.
loggerobjectObject with log method to use for logging.
Returnsstream.TransformA stream transform to capture the bundle file.

 

bundledJs(name, resultPath)

Stores the result path for the bundled js, for rendering later.

ArgumentTypeDescription
namestringName of the bundle.
resultPathstringPath to the bundled file.

 

bundledJsInStream(name, logger)stream.Transform

Stores the result path for the bundled js, for rendering later.

ArgumentTypeDescription
namestringName of the bundle.
loggerobjectObject with log method to use for logging.
Returnsstream.TransformA stream transform to capture the bundle file.

 

bundles(nameOrNames, opt)string

Returns HTML for the given bundles name(s) with CSS link tags first, then JS script tags.

ArgumentTypeDescription
nameOrNamesstring,Array.<string>Bundle name or array of names.
optobject,stringOptions object or .
opt.sourceTypestringThe type of files to output ('css', 'js').
opt.relativebooleanTrue to return a relative path.
ReturnsstringHTML of link and script tags that comprise the bundle.

 

createBundle(name, data)object

Creates a new bundle within the build.

ArgumentTypeDescription
namestringName of the bundle.
dataobjectData for the bundle.
ReturnsobjectThe bundle data.

 

cssBundles(nameOrNames)string

Returns CSS link tags HTML only for the given bundle name(s).

ArgumentTypeDescription
nameOrNamesstring,Array.<string>Bundle name or array of names.
ReturnsstringHTML of link tags that comprise the bundle.

 

dest(pattern)string

Returns a relative path derived from the build's destDir.

ArgumentTypeDescription
patternstringThe path pattern within the destination.
ReturnsstringThe relative destination path with pattern appended.

dest examples

gulp.task('clean-all', function () {
  del.sync([
    // Returns 'dist/**/*' for the default configuration...
    build.dest('/**/*')
  ]);
});

 

destLocale(pattern)

Returns a relative path derived from the build's locale directory.

ArgumentTypeDescription
patternstringThe path pattern within the locale destination.

destLocale examples

gulp.task(mts('fonts'), function () {
  return gulp.src([
    'src/lib/fonts/**/*'
  ])
  .pipe(gulpif(gzipOn, gzip(gzipOpt)))
  .pipe(gulp.dest(
    // Returns 'dist/en/lib/fonts/' when the 'en' locale is set...
    build.destLocale('/lib/fonts/')
  ));
});

 

findMinifiedFromSource(bundleItem)string,undefined

If bundle item has no min path, finds one, updates the item and returns.

ArgumentTypeDescription
bundleItemobjectThe bundle item with src to find min from.
Returnsstring, undefinedThe minified path, if found.

 

fsPath(urlPath)string

Returns a filesystem path for the given path string, taking any pathMap mappings into account.

ArgumentTypeDescription
urlPathstringThe url path string.
ReturnsstringThe filesystem path.

 

getBundleInfo(name, sourceType)

Returns an object containing information about the bundle. e.g. `{name,data,min,minif,sources,dest,fileName,relFile,relDir}`

ArgumentTypeDescription
namestringName of the bundle.
sourceTypestringThe type of files to output ('css', 'js').
ReturnsThe bundle info.

 

getBundleMinified(name, sourceType)Array.<string>

Returns just the min paths of the given bundle name.

ArgumentTypeDescription
namestringName of the bundle.
sourceTypestringThe type of files to output ('css', 'js').
ReturnsArray.<string>Array of pre-minified file paths for a bundle.

 

getBundleSources(name, sourceType)Array.<string>

Returns just the src paths of the given bundle name.

ArgumentTypeDescription
namestringName of the bundle.
sourceTypestringThe type of files to output ('css', 'js').
ReturnsArray.<string>Array of source paths for a bundle.

 

getBundleSourcesOrMinified(name, sourceType)Array.<string>

Returns the min (if any) OR src paths of the given bundle name.

ArgumentTypeDescription
namestringName of the bundle.
sourceTypestringThe type of files to output ('css', 'js').
ReturnsArray.<string>An array of source or pre-minified file paths for the bundle.

 

getPathMapping(pathType, pathStr)object

Returns the mappings that match url path.

ArgumentTypeDescription
pathTypestringThe type of pathStr ('fs', 'url').
pathStrstringThe path to get the mapping for.
ReturnsobjectThe path mapping object with keys: 'fs', 'url'.

 

getWatchPaths()Array.<string>

Returns an array of paths outside of src that are watched in dev mode.

ReturnsArray.<string>An array of paths that are watched in dev mode.

 

jsBundles(nameOrNames)string

Returns Javascript script tags HTML only for the given bundle name(s).

ArgumentTypeDescription
nameOrNamesstring,Array.<string>Bundle name or array of names.
ReturnsstringHTML of script tags that comprise the bundle.

 

link(srcPath, relative)string

Returns HTML for a link tag with a dynamic href attribute.

ArgumentTypeDescription
srcPathstringRelative path to the css file.
relativebooleanTrue to output a relative path.
ReturnsstringAn HTML link tag string.

 

notPath(pathStr)string

Returns a glob that excludes the given path string.

ArgumentTypeDescription
pathStrstringThe path to exclude.
ReturnsstringThe pathStr with exclusion pattern applied.

 

relativePath(targetPath)string

Returns a relative path derived from the build's baseDir.

ArgumentTypeDescription
targetPathstringThe path to get a relative path to.
ReturnsstringA relative path to targetPath.

 

relativePattern(basePath, pattern)string

Returns a relative path pattern derived from the build's baseDir. (e.g. '../path/to/##/#.js' but with asterisks instead of hashes)

ArgumentTypeDescription
basePathstringThe base path.
patternstringThe glob pattern.
ReturnsstringA relative path pattern within baseDir.

 

removeBundle(name)

Removes a bundle from the build.

ArgumentTypeDescription
namestringName of the bundle.

 

resolvePath(targetPath)string

Returns an absolute file-system path resolved from the build's baseDir.

ArgumentTypeDescription
targetPathstringThe path to resolve to.
ReturnsstringAn absolute path to the targetPath.

 

resolveSrcPath(srcPath)string

Returns an absolute file-system path resolved from sourceDir.

ArgumentTypeDescription
srcPathstringThe path to resolve.
ReturnsstringTh absolute path to the given srcPath.

 

runtimePath(pathStr, opt)string

Returns the given pathStr with pathTokens replaced for use at runtime.

ArgumentTypeDescription
pathStrstringThe path string.
optobjectOptions.
opt.bundlestringA bundle name for string replacement.
opt.bundleVerstringA bundle version for string replacement.
opt.bundlePathstringA bundle path for string replacement.
ReturnsstringThe pathStr with runtime path tokens replaced.

 

saveBundles()

Saves bundles to the configuration filePath.

 

script(srcPath, relative)string

Returns HTML for a script tag with a dynamic src attribute.

ArgumentTypeDescription
srcPathstringRelative path to the js file.
relativebooleanTrue to output a relative path.
ReturnsstringAn HTML script tag string.

 

src(pattern)string

Returns a relative path derived from the build's sourceDir.

ArgumentTypeDescription
patternstringPath pattern within the source directory.
ReturnsstringA relative source directory path.

src examples

gulp.task(mts('images'), function () {
  return gulp.src([
    // Returns 'src/**/*.gif' and so on....
    build.src('/**/*.gif'),
    build.src('/**/*.ico'),
    build.src('/**/*.jpg'),
    build.src('/**/*.png')
  ])
  .pipe(gulpif(gzipOn, gzip(gzipOpt)))
  .pipe(gulp.dest(build.destLocale()));
});

 

translate(str, etc)string

Applies the i18n translate method (`__`).

ArgumentTypeDescription
strstring,objString or phrase object with mustache template.
etcAn object or primitive value to merge into the template.
ReturnsstringThe translation.

 

translateNumeric(singular, plural, value)string

Applies the i18n translate-numeric method (`__n`).

ArgumentTypeDescription
singularstringThe singular format string.
pluralstringThe plural format string.
valuenumberThe number to translate.
ReturnsstringThe translation.

 

tryRequireNew(pathStr)object

Attempts to require an uncached instance of the given pathStr's module using require-new.

ArgumentTypeDescription
pathStrstringThe path string.
ReturnsobjectThe required javascript module or JSON file data.

 

trySetLocale(locale, errback)boolean

Sets the current locale for i18n.

ArgumentTypeDescription
localestringThe locale id string.
errbackfunctionA callback that accepts (err, locale);
ReturnsbooleanTrue if successful otherwise false.

trySetLocale examples

/** Sets a default or specific locale via cli flag `gulp [task] --locale=en` */
build.trySetLocale(gutil.env.locale, function (err) {
  if (!err)
    return;
  gutil.log(err);
  process.exit(1001);
});

 

versionToHashId(version)string

Returns a hash of the given version using Hashids.

ArgumentTypeDescription
versionstringA version string, e.g. '1.0.1'.
ReturnsstringThe hash value.

 

versionToInt(version)number

Returns the given version as an integer.

ArgumentTypeDescription
versionstringA version string, e.g. '1.0.1'.
ReturnsnumberThe version as an integer.

 

writeFileSync()

Do not use. This function is not finished.

Static Fields

 

current StaticBuild

The current (most recently created) instance of StaticBuild.

Static Methods

 

appendFilename(pathStr, valueToAppend)string

Returns the pathStr after appending the given value to the fileName, before the extension.

ArgumentTypeDescription
pathStrstringThe file path.
valueToAppendstringThe value to append.
ReturnsstringThe pathStr with value appended.

 

appendFilenamePart(pathStr, valueToAppend)string

Returns the pathStr with the given part appended to the fileName, before the extension, using a standard dash as a delimiter.

ArgumentTypeDescription
pathStrstringThe file path.
valueToAppendstringThe value to append.
ReturnsstringThe pathStr with value appended.

 

tryRequireNew(pathStr)object

Attempts to require an uncached instance of the given pathStr's module using require-new.

ArgumentTypeDescription
pathStrstringThe path string.
ReturnsobjectThe required javascript module or JSON file data.
Copyright @ Devoptix LLC 2016This site built with staticbuild.staticbuild.github.io v0.0.2 (en)  Help