-
-
Notifications
You must be signed in to change notification settings - Fork 94
/
develop.js
354 lines (338 loc) · 12.3 KB
/
develop.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
const webpack = require("webpack");
const middleware = require("webpack-dev-middleware");
const path = require("path");
const HTMLWebpackPlugin = require("html-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const PrerenderSPAPlugin = require("prerender-spa-plugin");
const merge = require("webpack-merge");
const { InjectManifest } = require("workbox-webpack-plugin");
const FaviconsWebpackPlugin = require("favicons-webpack-plugin");
const AddFilesPlugin = require("./add-files-plugin.js");
const ImageminPlugin = require("imagemin-webpack-plugin").default;
const imageminMozjpeg = require("imagemin-mozjpeg");
const express = require("express");
const ClosurePlugin = require("closure-webpack-plugin");
const readline = require("readline");
module.exports = { start, run };
function start({ routes, debug, customPort, manifestConfig, routesWithRequests, filesToGenerate }) {
const config = webpackOptions(false, routes, {
debug,
manifestConfig,
routesWithRequests,
filesToGenerate
});
const compiler = webpack(config);
const options = {
contentBase: false,
hot: true,
inline: true,
host: "localhost",
stats: "errors-only",
publicPath: "/"
};
const app = express();
app.use('/images', express.static(path.resolve(process.cwd(), "./images")));
app.use(require("webpack-dev-middleware")(compiler, options));
app.use(require("webpack-hot-middleware")(compiler, {
log: console.log, path: '/__webpack_hmr'
}))
app.use("*", function(req, res, next) {
// don't know why this works, but it does
// see: https://github.com/jantimon/html-webpack-plugin/issues/145#issuecomment-170554832
const filename = path.join(compiler.outputPath, "index.html");
compiler.outputFileSystem.readFile(filename, function(err, result) {
if (err) {
return next(err);
}
res.set("content-type", "text/html");
res.send(result);
res.end();
});
});
const port = customPort || 3000;
app.listen(port, () =>
console.log(`🚀 elm-pages develop on http://localhost:${port}`)
);
// https://stackoverflow.com/questions/43667102/webpack-dev-middleware-and-static-files
// app.use(express.static(__dirname + "/path-to-static-folder"));
}
function run({ routes, manifestConfig, routesWithRequests, filesToGenerate }, callback) {
webpack(
webpackOptions(true, routes, {
debug: false,
manifestConfig,
routesWithRequests,
filesToGenerate
})
).run((err, stats) => {
if (err) {
console.error(err);
process.exit(1);
} else {
callback();
}
console.log(
stats.toString({
chunks: false, // Makes the build much quieter
colors: true, // Shows colors in the console
// copied from `'minimal'`
all: false,
modules: false,
performance: true,
timings: false,
outputPath: true,
maxModules: 0,
errors: true,
warnings: true,
// our additional options
moduleTrace: false,
errorDetails: false
})
);
const duration = roundToOneDecimal(
(stats.endTime - stats.startTime) / 1000
);
console.log(`Duration: ${duration}s`);
});
}
function roundToOneDecimal(n) {
return Math.round(n * 10) / 10;
}
function printProgress(progress, message) {
readline.clearLine(process.stdout);
readline.cursorTo(process.stdout, 0);
process.stdout.write(`${progress} ${message}`);
}
function webpackOptions(
production,
routes,
{ debug, manifestConfig, routesWithRequests, filesToGenerate }
) {
const common = {
mode: production ? "production" : "development",
plugins: [
new AddFilesPlugin(routesWithRequests, filesToGenerate),
new CopyPlugin([
{
from: "static/**/*",
transformPath(targetPath, absolutePath) {
// TODO this is a hack... how do I do this with proper config of `to` or similar?
return targetPath.substring(targetPath.indexOf("/") + 1);
}
}
]),
new CopyPlugin([
{
from: "images/",
to: "images/"
}
]),
new ImageminPlugin({
test: /\.(jpe?g|png|gif|svg)$/i,
cacheFolder: path.resolve(process.cwd(), "./.cache"),
disable: !production,
pngquant: {
quality: "50-70",
speed: 7
},
plugins: [
imageminMozjpeg({
quality: 75,
progressive: false
})
]
}),
new HTMLWebpackPlugin({
inject: "head",
template: path.resolve(__dirname, "template.html")
}),
new FaviconsWebpackPlugin({
logo: path.resolve(process.cwd(), `./${manifestConfig.sourceIcon}`),
favicons: {
path: "/", // Path for overriding default icons path. `string`
appName: manifestConfig.name, // Your application's name. `string`
appShortName: manifestConfig.short_name, // Your application's short_name. `string`. Optional. If not set, appName will be used
appDescription: manifestConfig.description, // Your application's description. `string`
developerName: null, // Your (or your developer's) name. `string`
developerURL: null, // Your (or your developer's) URL. `string`
dir: "auto", // Primary text direction for name, short_name, and description
lang: "en-US", // Primary language for name and short_name
background: manifestConfig.background_color, // Background colour for flattened icons. `string`
theme_color: manifestConfig.theme_color, // Theme color user for example in Android's task switcher. `string`
appleStatusBarStyle: "black-translucent", // Style for Apple status bar: "black-translucent", "default", "black". `string`
display: manifestConfig.display, // Preferred display mode: "fullscreen", "standalone", "minimal-ui" or "browser". `string`
orientation: manifestConfig.orientation, // Default orientation: "any", "natural", "portrait" or "landscape". `string`
scope: manifestConfig.serviceworker.scope, // set of URLs that the browser considers within your app
start_url: manifestConfig.start_url, // Start URL when launching the application from a device. `string`
version: "1.0", // Your application's version string. `string`
logging: true, // Print logs to console? `boolean`
pixel_art: false, // Keeps pixels "sharp" when scaling up, for pixel art. Only supported in offline mode.
loadManifestWithCredentials: false, // Browsers don't send cookies when fetching a manifest, enable this to fix that. `boolean`
icons: {
// Platform Options:
// - offset - offset in percentage
// - background:
// * false - use default
// * true - force use default, e.g. set background for Android icons
// * color - set background for the specified icons
// * mask - apply mask in order to create circle icon (applied by default for firefox). `boolean`
// * overlayGlow - apply glow effect after mask has been applied (applied by default for firefox). `boolean`
// * overlayShadow - apply drop shadow after mask has been applied .`boolean`
//
android: true, // Create Android homescreen icon. `boolean` or `{ offset, background, mask, overlayGlow, overlayShadow }`
appleIcon: true, // Create Apple touch icons. `boolean` or `{ offset, background, mask, overlayGlow, overlayShadow }`
appleStartup: false, // Create Apple startup images. `boolean` or `{ offset, background, mask, overlayGlow, overlayShadow }`
coast: false, // Create Opera Coast icon. `boolean` or `{ offset, background, mask, overlayGlow, overlayShadow }`
favicons: true, // Create regular favicons. `boolean` or `{ offset, background, mask, overlayGlow, overlayShadow }`
firefox: false, // Create Firefox OS icons. `boolean` or `{ offset, background, mask, overlayGlow, overlayShadow }`
windows: false, // Create Windows 8 tile icons. `boolean` or `{ offset, background, mask, overlayGlow, overlayShadow }`
yandex: false // Create Yandex browser icon. `boolean` or `{ offset, background, mask, overlayGlow, overlayShadow }`
}
}
}),
new InjectManifest({
swSrc: path.resolve(__dirname, "./service-worker-template.js"),
include: [/^index\.html$/],
exclude: [
/android-chrome-.*\.png$/,
/apple-touch-icon.*\.png/,
/assets\//
],
swDest: "service-worker.js"
})
// comment this out to do performance profiling
// (drag-and-drop `events.json` file into Chrome performance tab)
// , new webpack.debug.ProfilingPlugin()
],
output: {
publicPath: "/"
},
resolve: {
modules: [
path.resolve(process.cwd(), `./node_modules`),
// TODO: find a cleaner way to do this.
// This line just needs a way to point to the `node_modules` directory
// for the library bin (not the user's node_modules, which is the
// process.cwd prefixed node_modules above).
path.resolve(path.dirname(require.resolve('webpack')), '../../'),
],
extensions: [".js", ".elm", ".scss", ".png", ".html"]
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: require.resolve("babel-loader")
}
},
{
test: /\.scss$/,
exclude: [/elm-stuff/],
// see https://github.com/webpack-contrib/css-loader#url
loaders: [
require.resolve("style-loader"),
require.resolve("css-loader"),
require.resolve("sass-loader")
]
},
{
test: /\.css$/,
exclude: [/elm-stuff/],
loaders: [
require.resolve("style-loader"),
require.resolve("css-loader")
]
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
exclude: [/elm-stuff/, /node_modules/],
loader: require.resolve("file-loader")
}
]
}
};
if (production) {
return merge(common, {
entry: "./index.js",
optimization: {
minimizer: [
new ClosurePlugin(
{ mode: "STANDARD" },
{
// compiler flags here
//
// for debuging help, try these:
//
// formatting: 'PRETTY_PRINT'
// debug: true,
// renaming: false
}
)
]
},
plugins: [
new webpack.ProgressPlugin({
entries: true,
modules: true,
modulesCount: 100,
profile: true,
handler: (percentage, message, ...args) => {
printProgress(`${Math.floor(percentage * 100)}%`, message);
}
}),
new PrerenderSPAPlugin({
staticDir: path.join(process.cwd(), "dist"),
routes: routes,
renderAfterDocumentEvent: "prerender-trigger"
})
],
module: {
rules: [
{
test: /\.elm$/,
exclude: [/elm-stuff/, /node_modules/],
use: {
loader: require.resolve("elm-webpack-loader"),
options: {
optimize: true
}
}
}
]
}
});
} else {
return merge(common, {
entry: [
require.resolve("webpack-hot-middleware/client"),
"./index.js",
],
plugins: [
new webpack.NamedModulesPlugin(),
// Prevents compilation errors causing the hot loader to lose state
new webpack.NoEmitOnErrorsPlugin(),
new webpack.HotModuleReplacementPlugin()
],
module: {
rules: [
{
test: /\.elm$/,
exclude: [/elm-stuff/, /node_modules/],
use: [
{ loader: require.resolve("elm-hot-webpack-loader") },
{
loader: require.resolve("elm-webpack-loader"),
options: {
debug: debug,
forceWatch: true
}
}
]
}
]
}
});
}
}