(config: ResolvedConfig)
| 1280 | * Support `%ENV_NAME%` syntax in html files |
| 1281 | */ |
| 1282 | export function htmlEnvHook(config: ResolvedConfig): IndexHtmlTransformHook { |
| 1283 | const pattern = /%(\S+?)%/g |
| 1284 | const envPrefix = resolveEnvPrefix({ envPrefix: config.envPrefix }) |
| 1285 | const env: Record<string, any> = { ...config.env } |
| 1286 | |
| 1287 | // account for user env defines |
| 1288 | for (const key in config.define) { |
| 1289 | if (key.startsWith(`import.meta.env.`)) { |
| 1290 | const val = config.define[key] |
| 1291 | if (typeof val === 'string') { |
| 1292 | try { |
| 1293 | const parsed = JSON.parse(val) |
| 1294 | env[key.slice(16)] = typeof parsed === 'string' ? parsed : val |
| 1295 | } catch { |
| 1296 | env[key.slice(16)] = val |
| 1297 | } |
| 1298 | } else { |
| 1299 | env[key.slice(16)] = JSON.stringify(val) |
| 1300 | } |
| 1301 | } |
| 1302 | } |
| 1303 | return (html, ctx) => { |
| 1304 | return html.replace(pattern, (text, key) => { |
| 1305 | if (key in env) { |
| 1306 | return env[key] |
| 1307 | } else { |
| 1308 | if (envPrefix.some((prefix) => key.startsWith(prefix))) { |
| 1309 | const relativeHtml = normalizePath( |
| 1310 | path.relative(config.root, ctx.filename), |
| 1311 | ) |
| 1312 | config.logger.warn( |
| 1313 | colors.yellow( |
| 1314 | colors.bold( |
| 1315 | `(!) ${text} is not defined in env variables found in /${relativeHtml}. ` + |
| 1316 | `Is the variable mistyped?`, |
| 1317 | ), |
| 1318 | ), |
| 1319 | ) |
| 1320 | } |
| 1321 | |
| 1322 | return text |
| 1323 | } |
| 1324 | }) |
| 1325 | } |
| 1326 | } |
| 1327 | |
| 1328 | export function injectNonceAttributeTagHook( |
| 1329 | config: ResolvedConfig, |
no test coverage detected