js.Babel
Transpile JavaScript resources using Babel.
Syntax
js.Babel [OPTIONS] RESOURCE
Returns
resource.Resource
Alias
babel
The js.Babel function transforms JavaScript using Babel.
Setup
- Step 1
- Install Node.js.
- Step 2
- Install the required Node packages in the root of your project. For example, to install Babel’s core compiler, its command-line interface, and the preset for transpiling modern JavaScript based on your target environments:
npm install --save-dev @babel/core @babel/cli @babel/preset-env - Step 3
- Create a Babel configuration file in the root of your project. For example, to use the environment preset to target Google Chrome version 79 or later:babel.config.mjs
export default { presets: [ [ '@babel/preset-env', { targets: { chrome: "79" } } ] ] }; - Step 4
- Place your JS file within the
assets/jsdirectory. - Step 5
- Add the Babel executable to Hugo’s
security.exec.allowlist in your project configuration:security: exec: allow: - ^(dart-)?sass(-embedded)?$ - ^go$ - ^git$ - ^node$ - ^postcss$ - ^tailwindcss$ - ^babel$[security] [security.exec] allow = ['^(dart-)?sass(-embedded)?$', '^go$', '^git$', '^node$', '^postcss$', '^tailwindcss$', '^babel$']{ "security": { "exec": { "allow": [ "^(dart-)?sass(-embedded)?$", "^go$", "^git$", "^node$", "^postcss$", "^tailwindcss$", "^babel$" ] } } } - Step 6
- Create a partial template to process the JavaScript:layouts/_partials/js.html
{{ with resources.Get "js/main.js" }} {{ $opts := dict "minified" (cond hugo.IsDevelopment false true) "noComments" (cond hugo.IsDevelopment false true) "sourceMap" (cond hugo.IsDevelopment "inline" "none") }} {{ with . | js.Babel $opts }} {{ if hugo.IsDevelopment }} <script src="{{ .RelPermalink }}"></script> {{ else }} {{ with . | fingerprint }} <script src="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous"></script> {{ end }} {{ end }} {{ end }} {{ end }} - Step 7
- Call the partial template from your base template:layouts/baseof.html
<head> {{ partial "js.html" . }} </head>
Options
The js.Babel function accepts an options map.
compact- (
bool) Whether to remove optional newlines and whitespace. Enabled whenminifiedistrue. Default isfalse. config- (
string) The path to the Babel configuration file. By default, Hugo searches the root of the project directory and any modules forbabel.config.js,babel.config.mjs, andbabel.config.cjsin that order. Use this option only to point to a configuration file with a custom name or one located in a custom subdirectory. minified- (
bool) Whether to minify transpiled code. Enables thecompactoption. Default isfalse. noBabelrc- (
bool) Whether to ignore.babelrcand.babelignorefiles. Default isfalse. noComments- (
bool) Whether to remove comments. Default isfalse. sourceMap- (
string) Whether to generate source maps, one ofexternal,inline, ornone. Default isnone. verbose- (
bool) Whether to enable verbose logging. Default isfalse.
