hugo/docs/content/en/hugo-pipes/transformjs.md
Niek de Wit 2a171ff1c5 resources: Add JavaScript transpiling solution
Add a new pipe called TranspileJS which uses the Babel cli. This makes it possible for users to write ES6 JavaScript code and transpile it to ES5 during website generation so that the code still works with older browser versions.

Fixes #5764
2020-04-29 10:51:33 +02:00

2.5 KiB
Executable file

title description date publishdate lastmod categories keywords menu weight sections_weight draft
TransformJS Hugo Pipes can process JS files with Babel. 2019-03-21 2019-03-21 2019-03-21
asset management
docs
parent weight
pipes 75
75 75 false

Any JavaScript resource file can be transpiled to another JavaScript version using resources.TransformJS which takes for argument the resource object and a slice of options listed below. TransformJS uses the babel cli.

{{% note %}} Hugo Pipe's TranspileJS requires the @babel/cli and @babel/core JavaScript packages to be installed in the environment (npm install -g @babel/cli @babel/core) along with any Babel plugin(s) or preset(s) used (e.g., npm install -g @babel/preset-env).

If you are using the Hugo Snap package, Babel and plugin(s) need to be installed locally within your Hugo site directory, e.g., npm install @babel/cli @babel/core without the -g flag. {{% /note %}}

Options

config [string]
Path to the Babel configuration file

If no configuration file is used:

plugins [string]
Comma seperated string of Babel plugins to use
presets [string]
Comma seperated string of Babel presets to use
minified [bool]
Save as much bytes as possible when printing
noComments [bool]
Write comments to generated output (true by default)
compact [string]
Do not include superfluous whitespace characters and line terminators (true/false/auto)
verbose [bool]
Log everything

Examples

Without a .babelrc file, you can simply pass the options like so:

{{- $transpileOpts := (dict "presets" "@babel/preset-env" "minified" true "noComments" true "compact" "true" ) -}}
{{- $transpiled := resources.Get "scripts/main.js" | transpileJS $transpileOpts -}}

If you rather want to use a config file, you can leave out the options in the template.

{{- $transpiled := resources.Get "scripts/main.js" | transpileJS $transpileOpts -}}

Then, you can either create a .babelrc in the root of your project, or your can create a .babel.config.js. More information on these configuration files can be found here: babel configuration

Finally, you can also pass a custom file path to a config file like so:

{{- $transpileOpts := (dict "config" "config/my-babel-config.js" ) -}}
{{- $transpiled := resources.Get "scripts/main.js" | transpileJS $transpileOpts -}}