forked from dfinity/internet-identity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebpack.config.ts
238 lines (219 loc) · 7.32 KB
/
webpack.config.ts
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
import path from "path";
import * as fs from "fs";
import webpack from "webpack";
import CopyPlugin from "copy-webpack-plugin";
import CompressionPlugin from "compression-webpack-plugin";
import HtmlWebpackPlugin from "html-webpack-plugin";
import MiniCssExtractPlugin from "mini-css-extract-plugin";
import CssMinimizerPlugin from "css-minimizer-webpack-plugin";
import { fileURLToPath } from "url";
import { config } from "dotenv";
import { TemplateResult } from "lit-html";
import { render } from "@lit-labs/ssr/lib/render-lit-html";
import { pageContent as aboutStaticContent } from "./src/frontend/src/flows/about";
import { pageContent as faqStaticContent } from "./src/frontend/src/flows/faq";
const __dirname = fileURLToPath(new URL(".", import.meta.url));
config();
/** Read the II canister ID from dfx's local state */
function readCanisterId() {
const canisterIdsJson = "./.dfx/local/canister_ids.json";
let canisterId;
try {
canisterId = JSON.parse(fs.readFileSync(canisterIdsJson).toString())
.internet_identity.local;
} catch (e) {
throw Error(`Could get canister ID from ${canisterIdsJson}: ${e}`);
}
console.log("Read canister ID:", canisterId);
return canisterId;
}
// A plugin that replaces content in HTML files
class HtmlReplacePlugin {
constructor(
/** The function to apply on the HTML */
private f: (html: string) => string,
/** If specified, only replace HTML in this file */
private name?: string
) {}
apply(compiler: webpack.Compiler) {
compiler.hooks.compilation.tap(this.constructor.name, (compilation) => {
HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
this.constructor.name,
(data, cb) => {
if (this.name === undefined || this.name === data.outputName) {
data.html = this.f(data.html);
}
cb(null, data);
}
);
});
}
}
// A plugin that creates an HTML page based on our index.html template
const htmlPlugin = ({ filename }: { filename: string }): HtmlWebpackPlugin =>
new HtmlWebpackPlugin({
template: "src/frontend/assets/index.html",
// Don't inject the index.js in production, because the canister actually injects it (see http.rs for more details)
// When true, injects (a hot-reloading version of) the built javascript, which in turn inserts the CSS (through "style-loader").
// This value is read by the template; see index.html for more details.
inject: !isProduction,
filename,
});
// A plugin that creates a static page by injecting a static TemplateResult into a page
const staticPagePlugin = (
pageName: string,
pageContent: TemplateResult
): HtmlReplacePlugin =>
new HtmlReplacePlugin((html) => {
const content = Array.from(render(pageContent)).reduce(
(acc, v) => acc + v,
""
);
return html.replace(
'<main id="pageContent" class="l-wrap" aria-live="polite"></main>',
`<main id="pageContent" class="l-wrap" aria-live="polite">${content}</main>`
);
}, pageName);
// This emulates the behaviour of http.rs while using webpack dev server locally
// so we don't need to proxy to the backend canister for the index.html file.
// This overcomes some issues with Safari and the CSP headers set in http.rs.
const injectCanisterIdPlugin = () =>
new HtmlReplacePlugin((html) =>
html.replace(
'<script id="setupJs"></script>',
`<script data-canister-id="${readCanisterId()}" id="setupJs"></script>`
)
);
const staticAboutPlugin = () =>
staticPagePlugin("about.html", aboutStaticContent);
const staticFaqPlugin = () => staticPagePlugin("faq.html", faqStaticContent);
const isProduction = process.env.NODE_ENV === "production";
const devtool = isProduction ? undefined : "source-map";
/* Default configuration */
const defaults = {
mode: isProduction ? "production" : "development",
devtool,
optimization: {
minimize: isProduction,
minimizer: [new CssMinimizerPlugin(), "..."],
},
output: { clean: true },
resolve: {
extensions: [".js", ".ts"],
fallback: {
stream: "stream-browserify",
},
},
module: {
rules: [
{ test: /\.(ts)$/, loader: "ts-loader" },
{
test: /\.css$/,
use: [
isProduction ? MiniCssExtractPlugin.loader : "style-loader",
"css-loader",
],
},
{
test: /\.(png|jpg|gif)$/i,
type: "asset/resource",
},
],
},
plugins: [
...(isProduction ? [new MiniCssExtractPlugin()] : []),
new webpack.ProvidePlugin({
Buffer: ["buffer", "Buffer"],
process: "process/browser",
}),
new webpack.EnvironmentPlugin({
// Whether or not static pages should be hydrated
// (only done in production since we don't have statically rendered
// pages for development)
HYDRATE_STATIC_PAGES: isProduction ? "1" : "0",
// Feature flags (see README)
II_FETCH_ROOT_KEY: "0",
II_DUMMY_AUTH: "0",
II_DUMMY_CAPTCHA: "0",
II_VERSION: "",
}),
new CompressionPlugin({
test: /\.js(\?.*)?$/i,
}),
new webpack.IgnorePlugin({
checkResource(resource) {
return /.*\/wordlists\/(?!english).*\.json/.test(resource);
},
}),
new CopyPlugin({
patterns: [
{
from: path.join(__dirname, "src", "frontend", "assets"),
to: path.join(__dirname, "dist"),
// We want html files from HtmlWebpackPlugin, not the original ones
filter: (resourcePath) => {
return !resourcePath.endsWith(".html");
},
},
],
}),
htmlPlugin({ filename: "index.html" }),
htmlPlugin({ filename: "about.html" }),
htmlPlugin({ filename: "faq.html" }),
],
};
export default [
{
...defaults,
name: "app",
entry: {
index: path.join(__dirname, "src", "frontend", "src", "index"),
},
devServer: {
magicHtml: false,
static: false,
// Set up a proxy that redirects API calls to the replica.
proxy: {
// Make sure /api calls land on the replica (and not on webpack)
"/api": "http://localhost:4943",
},
historyApiFallback: {
// Make sure that visiting links like `/faq` serves the correct HTML
// (could also be `/index.html` since the content is the same in development, but it's
// less confusing to show the correct file)
rewrites: [
{ from: /\/about/, to: "/about.html" },
{ from: /\/faq/, to: "/faq.html" },
],
},
},
plugins: [
...defaults.plugins,
// In production, we generate static versions of our static pages (during development we
// prefer hot-reloading dynamic pages);
// in development, we inject canister ID when using the dev server, so that the local
// file can be used (instead of the HTML served by the canister)
...(isProduction
? [staticAboutPlugin(), staticFaqPlugin()]
: [injectCanisterIdPlugin()]),
],
},
{
...defaults,
name: "showcase",
plugins: [
...defaults.plugins,
new webpack.EnvironmentPlugin({
BASE_URL: "",
}),
],
entry: {
showcase: path.join(__dirname, "src", "frontend", "src", "showcase"),
},
devServer: {
magicHtml: false,
static: false,
historyApiFallback: true, // serves the app on all routes, which we use because the app itself does the routing
},
},
];