Skip to content

Commit 6add6d7

Browse files
committed
Rename transpileJS to babel
And add a test. Updates #5764
1 parent 2a171ff commit 6add6d7

File tree

8 files changed

+233
-119
lines changed

8 files changed

+233
-119
lines changed

‎common/hugo/hugo.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ package hugo
1616
import (
1717
"fmt"
1818
"html/template"
19+
"os"
20+
21+
"github.com/gohugoio/hugo/config"
1922
)
2023

2124
const (
@@ -69,3 +72,9 @@ func NewInfo(environment string) Info {
6972
Environment: environment,
7073
}
7174
}
75+
76+
func GetExecEnviron(cfg config.Provider) []string {
77+
env := os.Environ()
78+
config.SetEnvVars(&env, "HUGO_ENVIRONMENT", cfg.GetString("environment"))
79+
return env
80+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
---
2+
title: Babel
3+
description: Hugo Pipes can process JS files with Babel.
4+
date: 2019-03-21
5+
publishdate: 2019-03-21
6+
lastmod: 2019-03-21
7+
categories: [asset management]
8+
keywords: []
9+
menu:
10+
docs:
11+
parent: "pipes"
12+
weight: 49
13+
weight: 49
14+
sections_weight: 49
15+
draft: false
16+
---
17+
18+
Any JavaScript resource file can be transpiled to another JavaScript version using `resources.Babel` which takes for argument the resource object and an optional dict of options listed below. Babel uses the [babel cli](https://babeljs.io/docs/en/babel-cli).
19+
20+
21+
{{% note %}}
22+
Hugo Pipe's Babel requires the `@babel/cli` and `@babel/core` JavaScript packages to be installed in the project or globally (`npm install -g @babel/cli @babel/core`) along with any Babel plugin(s) or preset(s) used (e.g., `npm install @babel/preset-env --save-dev`).
23+
24+
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 --save-dev` without the `-g` flag.
25+
{{% /note %}}
26+
27+
### Options
28+
29+
config [string]
30+
: Path to the Babel configuration file. Hugo will, by default, look for a `babel.config.js` in your project. More information on these configuration files can be found here: [babel configuration](https://babeljs.io/docs/en/configuration).
31+
32+
minified [bool]
33+
: Save as much bytes as possible when printing
34+
35+
noComments [bool]
36+
: Write comments to generated output (true by default)
37+
38+
compact [bool]
39+
: Do not include superfluous whitespace characters and line terminators. Defaults to `auto` if not set.
40+
41+
verbose [bool]
42+
: Log everything
43+
44+
### Examples
45+
46+
```go-html-template
47+
{{- $transpiled := resources.Get "scripts/main.js" | babel -}}
48+
```
49+
50+
Or with options:
51+
52+
```go-html-template
53+
{{ $opts := dict "noComments" true }}
54+
{{- $transpiled := resources.Get "scripts/main.js" | babel $opts -}}
55+
```

‎docs/content/en/hugo-pipes/transformjs.md‎

Lines changed: 0 additions & 69 deletions
This file was deleted.
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
// Copyright 2020 The Hugo Authors. All rights reserved.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
14+
package hugolib
15+
16+
import (
17+
"os"
18+
"os/exec"
19+
"path/filepath"
20+
"runtime"
21+
"testing"
22+
23+
"github.com/gohugoio/hugo/htesting"
24+
25+
"github.com/spf13/viper"
26+
27+
qt "github.com/frankban/quicktest"
28+
29+
"github.com/gohugoio/hugo/hugofs"
30+
31+
"github.com/gohugoio/hugo/common/loggers"
32+
)
33+
34+
func TestResourceChainBabel(t *testing.T) {
35+
if !isCI() {
36+
t.Skip("skip (relative) long running modules test when running locally")
37+
}
38+
39+
if runtime.GOOS == "windows" {
40+
t.Skip("skip npm test on Windows")
41+
}
42+
43+
wd, _ := os.Getwd()
44+
defer func() {
45+
os.Chdir(wd)
46+
}()
47+
48+
c := qt.New(t)
49+
50+
packageJSON := `{
51+
"scripts": {},
52+
53+
"devDependencies": {
54+
"@babel/cli": "7.8.4",
55+
"@babel/core": "7.9.0",
56+
"@babel/preset-env": "7.9.5"
57+
}
58+
}
59+
`
60+
61+
babelConfig := `
62+
console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT );
63+
64+
module.exports = {
65+
presets: ["@babel/preset-env"],
66+
};
67+
68+
`
69+
70+
js := `
71+
/* A Car */
72+
class Car {
73+
constructor(brand) {
74+
this.carname = brand;
75+
}
76+
}
77+
`
78+
79+
workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-test-babel")
80+
c.Assert(err, qt.IsNil)
81+
defer clean()
82+
83+
v := viper.New()
84+
v.Set("workingDir", workDir)
85+
v.Set("disableKinds", []string{"taxonomyTerm", "taxonomy", "page"})
86+
b := newTestSitesBuilder(t).WithLogger(loggers.NewWarningLogger())
87+
88+
// Need to use OS fs for this.
89+
b.Fs = hugofs.NewDefault(v)
90+
b.WithWorkingDir(workDir)
91+
b.WithViper(v)
92+
b.WithContent("p1.md", "")
93+
94+
b.WithTemplates("index.html", `
95+
{{ $options := dict "noComments" true }}
96+
{{ $transpiled := resources.Get "js/main.js" | babel -}}
97+
Transpiled: {{ $transpiled.Content | safeJS }}
98+
99+
`)
100+
101+
jsDir := filepath.Join(workDir, "assets", "js")
102+
b.Assert(os.MkdirAll(jsDir, 0777), qt.IsNil)
103+
b.WithSourceFile("assets/js/main.js", js)
104+
b.WithSourceFile("package.json", packageJSON)
105+
b.WithSourceFile("babel.config.js", babelConfig)
106+
107+
b.Assert(os.Chdir(workDir), qt.IsNil)
108+
_, err = exec.Command("npm", "install").CombinedOutput()
109+
b.Assert(err, qt.IsNil)
110+
111+
out, err := captureStderr(func() error {
112+
return b.BuildE(BuildCfg{})
113+
114+
})
115+
// Make sure Node sees this.
116+
b.Assert(out, qt.Contains, "Hugo Environment: production")
117+
b.Assert(err, qt.IsNil)
118+
119+
b.AssertFileContent("public/index.html", `
120+
var Car = function Car(brand) {
121+
_classCallCheck(this, Car);
122+
123+
this.carname = brand;
124+
};
125+
`)
126+
127+
}

resources/resource_transformers/transpilejs/transpilejs.go renamed to resources/resource_transformers/babel/babel.go

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright 2018 The Hugo Authors. All rights reserved.
1+
// Copyright 2020 The Hugo Authors. All rights reserved.
22
//
33
// Licensed under the Apache License, Version 2.0 (the "License");
44
// you may not use this file except in compliance with the License.
@@ -11,14 +11,16 @@
1111
// See the License for the specific language governing permissions and
1212
// limitations under the License.
1313

14-
package transpilejs
14+
package babel
1515

1616
import (
1717
"io"
1818
"os"
1919
"os/exec"
2020
"path/filepath"
21+
"strconv"
2122

23+
"github.com/gohugoio/hugo/common/hugo"
2224
"github.com/gohugoio/hugo/resources/internal"
2325

2426
"github.com/mitchellh/mapstructure"
@@ -32,14 +34,13 @@ import (
3234

3335
// Options from https://babeljs.io/docs/en/options
3436
type Options struct {
35-
Config string //Custom path to config file
36-
Plugins string //Comma seperated string of plugins
37-
Presets string //Comma seperated string of presets
38-
Minified bool //true/false
39-
NoComments bool //true/false
40-
Compact string //true/false/auto
41-
Verbose bool //true/false
42-
NoBabelrc bool //true/false
37+
Config string // Custom path to config file
38+
39+
Minified bool
40+
NoComments bool
41+
Compact *bool
42+
Verbose bool
43+
NoBabelrc bool
4344
}
4445

4546
func DecodeOptions(m map[string]interface{}) (opts Options, err error) {
@@ -52,20 +53,14 @@ func DecodeOptions(m map[string]interface{}) (opts Options, err error) {
5253
func (opts Options) toArgs() []string {
5354
var args []string
5455

55-
if opts.Plugins != "" {
56-
args = append(args, "--plugins="+opts.Plugins)
57-
}
58-
if opts.Presets != "" {
59-
args = append(args, "--presets="+opts.Presets)
60-
}
6156
if opts.Minified {
6257
args = append(args, "--minified")
6358
}
6459
if opts.NoComments {
6560
args = append(args, "--no-comments")
6661
}
67-
if opts.Compact != "" {
68-
args = append(args, "--compact="+opts.Compact)
62+
if opts.Compact != nil {
63+
args = append(args, "--compact="+strconv.FormatBool(*opts.Compact))
6964
}
7065
if opts.Verbose {
7166
args = append(args, "--verbose")
@@ -103,7 +98,6 @@ func (t *babelTransformation) Key() internal.ResourceTransformationKey {
10398
// npm install -g @babel/preset-env
10499
// Instead of installing globally, you can also install everything as a dev-dependency (--save-dev instead of -g)
105100
func (t *babelTransformation) Transform(ctx *resources.ResourceTransformationCtx) error {
106-
107101
const localBabelPath = "node_modules/@babel/cli/bin/"
108102
const binaryName = "babel.js"
109103

@@ -164,6 +158,7 @@ func (t *babelTransformation) Transform(ctx *resources.ResourceTransformationCtx
164158

165159
cmd.Stdout = ctx.To
166160
cmd.Stderr = os.Stderr
161+
cmd.Env = hugo.GetExecEnviron(t.rs.Cfg)
167162

168163
stdin, err := cmd.StdinPipe()
169164
if err != nil {

‎resources/resource_transformers/postcss/postcss.go‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,9 @@ import (
2525
"strconv"
2626
"strings"
2727

28-
"github.com/gohugoio/hugo/common/loggers"
28+
"github.com/gohugoio/hugo/common/hugo"
2929

30-
"github.com/gohugoio/hugo/config"
30+
"github.com/gohugoio/hugo/common/loggers"
3131

3232
"github.com/gohugoio/hugo/resources/internal"
3333
"github.com/spf13/afero"
@@ -202,10 +202,7 @@ func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationC
202202

203203
cmd.Stdout = ctx.To
204204
cmd.Stderr = io.MultiWriter(os.Stderr, &errBuf)
205-
// TODO(bep) somehow generalize this to other external helpers that may need this.
206-
env := os.Environ()
207-
config.SetEnvVars(&env, "HUGO_ENVIRONMENT", t.rs.Cfg.GetString("environment"))
208-
cmd.Env = env
205+
cmd.Env = hugo.GetExecEnviron(t.rs.Cfg)
209206

210207
stdin, err := cmd.StdinPipe()
211208
if err != nil {

‎tpl/resources/init.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ func init() {
6060
[][2]string{},
6161
)
6262

63-
ns.AddMethodMapping(ctx.TranspileJS,
64-
[]string{"transpileJS"},
63+
ns.AddMethodMapping(ctx.Babel,
64+
[]string{"babel"},
6565
[][2]string{},
6666
)
6767

0 commit comments

Comments
 (0)