Joey LIU | NANTSOU


為了方便部署Hugo到AWS S3, 簡單寫了一個javascript的script。

主要用gulp來執行一些簡單的命令。

主要做的事行如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
const gulp = require("gulp");
const del = require("del");
const htmlmin = require("gulp-htmlmin");
const spawn = require("child_process").spawn;
const target = "public";

gulp.task("build", (cb) => {
    del([ target ]);
    const hugo = spawn("hugo", ["-t", "einfach"], {stdio: "inherit"});
    hugo.on("exit", function (code) {cb(code === 0?null : 'ERROR: Hugo process exited with code: ' + code)});
});

gulp.task("minify-html", () => {
    const minOptions = {
        collapseWhitespace: true,
        caseSensitive: true,
        minifyCSS: true,
        minifyJS: true
    };
    return gulp.src(`${target}/**/*.html`)
               .pipe(htmlmin(minOptions))
               .pipe(gulp.dest(target));
});

gulp.task("sync", (cb) => {
    const sync = spawn("aws", ["s3", "sync", "./public/", "s3://joeyliu.net", "--acl", "public-read", "--cache-control", "public,no-cache,max-age=604800", "--delete"], {stdio: "inherit"})
    sync.on("exit", function (code) {cb(code === 0 || code === 255 ? null : "ERROR: aws s3 sync process exited with code: " + code)})
});

gulp.task("clean-cache", (cb) => {
    const sync = spawn("aws", ["cloudfront", "create-invalidation", "--distribution-id", "EKCKL2MN34GEY", "--paths", "/*"], {stdio: "inherit"})
    sync.on("exit", function (code) {cb(code === 0 || code === 255 ? null : "ERROR: aws s3 sync process exited with code: " + code)})
});

gulp.task("build:minify", gulp.series("build", "minify-html"));
gulp.task("deploy", gulp.series("sync", "clean-cache"));

因為整個project是由package.json管理,所以就順便利用npm來執行gulp命令(不過這步驟倒是不需要)

{
    "scripts": {
        "build": "gulp build:minify",
        "deploy": "gulp sync:clean-cache"
    }
}