forked from popcorn-nantes/popcorn-nantes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.js
204 lines (186 loc) · 6.05 KB
/
build.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
require("dotenv").config();
const config = require("./config");
const nunjucks = require("nunjucks");
const fs = require("fs");
const fsExtra = require("fs-extra");
const sharp = require("sharp");
const path = require("path");
const rimraf = require("rimraf");
const {
postcssRun,
parseMarkdownDirectory,
shuffle,
} = require("./utils/helpers.js");
const FileMinifyLoader = require("nunjucks-minify-loaders").FileMinifyLoader;
const opts = {
minify: {
collapseWhitespace: true,
minifyCSS: true,
minifyJS: true,
removeComments: true,
},
};
const loader = new FileMinifyLoader("views", opts);
const views = new nunjucks.Environment(loader, {
autoescape: false,
});
views.addGlobal("SITE_NAME", config.SITE_NAME);
views.addGlobal("SITE_BASE_URL", process.env.SITE_BASE_URL);
views.addGlobal(
"CONTACT_ALL_FREELANCES_FORM_LINK",
process.env.CONTACT_ALL_FREELANCES_FORM_LINK
);
const BUILD_DIRECTORY = "_site";
const STATIC_DIRECTORY = "static";
/**
* BUILD STATIC SITE
*/
build();
async function build() {
const buildPromises = [];
rimraf.sync(path.resolve(`./${BUILD_DIRECTORY}`));
fs.mkdirSync(`./${BUILD_DIRECTORY}`);
console.log(`📁 deleted & recreated ${BUILD_DIRECTORY} directory`);
// copy all files and directories from /static diretory to build directory
fsExtra.copySync(
path.resolve(`./${STATIC_DIRECTORY}`),
path.resolve(`./${BUILD_DIRECTORY}`),
{
recursive: true,
}
);
console.log(`📁 static directory copied to ${BUILD_DIRECTORY} directory`);
// create html files from markdown files
buildPages();
console.log("📝 pages markdown files compiled to html.");
buildPersons();
console.log("📝 persons markdown files compiled html.");
// compiled and purge tailwind.css
console.log("🎨 starting postcss & purgecss ...");
const purgecssConfig = {
content: ["views/**/*.njk"],
defaultExtractor: (content) => content.match(/[\w-/:]+(?<!:)/g) || [],
};
buildPromises.push(
postcssRun("./static/app.css", "./_site/app.css", purgecssConfig).then(
(r) => {
console.log("🎨 postcss & purgecss done.");
}
)
);
// skip image optim in dev to get faster build times.
if (process.env.NODE_ENV !== "development") {
console.log("🖼️ starting images resizing and compression...");
buildPromises.push(
imagesOptimize().then((result) => {
const { imageCount, totalWebpSize, totalJpegSize } = result;
console.log(
`🖼️ images compression done: ${imageCount} images resized. Total webp thumbnails size: ${Math.ceil(
totalWebpSize / 1000
)}Ko. Total Jpeg thumbnails size: ${Math.ceil(
totalJpegSize / 1000
)}Ko `
);
})
);
}
return Promise.all(buildPromises).then((r) => {
console.log("✨ All build operations finished");
});
}
// resize and compress .jpeg & .png images for homepage listing,
// and create .webp versions of photos.
async function imagesOptimize() {
fs.mkdirSync(`./${BUILD_DIRECTORY}/media/thumbnails`, { recursive: true });
let totalWebpSize = 0;
let totalJpegSize = 0;
let imageCount = 0;
const sharpPromisesWebp = [];
const sharpPromisesJpeg = [];
fs.readdirSync(`./${BUILD_DIRECTORY}/media/photos`).forEach(function (
filename
) {
imageCount++;
const extension = path.extname(filename);
const basename = filename.replace(extension, "");
// compress all image to webp
sharpPromisesWebp.push(
sharp(`./${BUILD_DIRECTORY}/media/photos/` + filename)
.resize(300)
.toFile(`./${BUILD_DIRECTORY}/media/thumbnails/${basename}.webp`)
.then((info) => {
totalWebpSize += info.size;
return info;
})
);
// jpeg fallback for safari, does not support webp.
sharpPromisesJpeg.push(
sharp(`./${BUILD_DIRECTORY}/media/photos/` + filename)
.resize(300)
.toFile(`./${BUILD_DIRECTORY}/media/thumbnails/${basename}.jpeg`)
.then((info) => {
totalJpegSize += info.size;
return info;
})
);
});
await Promise.all([...sharpPromisesWebp, ...sharpPromisesJpeg]);
return { imageCount, totalWebpSize, totalJpegSize };
}
function buildPages() {
let entities = parseMarkdownDirectory("./content/pages");
entities.forEach((entity) => {
const html = views.render("page.njk", { entity });
fsExtra.outputFile(
`./${BUILD_DIRECTORY}/page/${entity.$slug}/index.html`,
html
);
});
}
function buildPersons() {
let resources = parseMarkdownDirectory("./content/persons");
resources.forEach((resource) => {
const photoExtension = path.extname(resource.photo);
const photoBasename = resource.photo.replace(photoExtension, "");
// will be user to build search index for the search engine.
resource.$search_keywords = [
...resource.domaines_metiers,
...resource.technologies,
resource.titre,
];
// those files will be created at build time.
resource.photo = {
default: `/media/photos/${resource.photo}`,
thumbnailJpeg: `/media/thumbnails/${photoBasename}.jpeg`,
thumbnailWebp: `/media/thumbnails/${photoBasename}.webp`,
};
resource.mail = Buffer.from(resource.mail).toString("base64");
resource.telephone = resource.telephone
? Buffer.from(resource.telephone.toString()).toString("base64")
: "";
});
// build a JSON index of person/keywords for the search engine
const searchIndexJson = resources.map((resource) => ({
id: resource.$slug,
keywords: resource.$search_keywords,
}));
fsExtra.outputFile(
`./${BUILD_DIRECTORY}/api/search-index.json`,
JSON.stringify(searchIndexJson)
);
// create homepage.
const html = views.render("index.njk", {
persons: shuffle(resources),
});
fsExtra.outputFile(`./${BUILD_DIRECTORY}/index.html`, html);
// create each person profile page
resources.forEach((person) => {
const personHtml = views.render("person.njk", {
entity: person,
});
fsExtra.outputFile(
`./${BUILD_DIRECTORY}/person/${person.$slug}/index.html`,
personHtml
);
});
}