diff --git a/plugins/env.ts b/plugins/env.ts new file mode 100644 index 000000000..584c54376 --- /dev/null +++ b/plugins/env.ts @@ -0,0 +1,31 @@ +import { Plugin } from '../types.ts'; + +export const defaultMatcher = /{{([^}]*)}}/ig; + +type Options = { + matcher?: string | RegExp, +} +const defaultOptions: Options = { + matcher: defaultMatcher, +} +const env = (options: Options = defaultOptions): Plugin => ({ + name: 'env', + test: /\.[tj]s[x]?$/, + acceptHMR: true, + async transform(content: Uint8Array) { + const parameters = Deno.env.toObject(); + const string = (new TextDecoder()).decode(content); + const code = string + .replaceAll(options.matcher!, (raw, match) => { + if (match in parameters) { + return String(parameters[match]); + } + return raw; + }); + return { + code, + } + } +}) + +export default env; diff --git a/plugins/env_test.ts b/plugins/env_test.ts new file mode 100644 index 000000000..29fb2e598 --- /dev/null +++ b/plugins/env_test.ts @@ -0,0 +1,38 @@ +import { assertEquals, assert } from 'https://deno.land/std/testing/asserts.ts'; +import env from './env.ts'; + +Deno.env.set('TEST_ENV_VAR', '1') + +Deno.test('env loader should accept ts files', async () => { + const plugin = env(); + assert(plugin.test.test('mod.ts')); +}) + +Deno.test('env loader should accept tsx files', async () => { + const plugin = env(); + assert(plugin.test.test('mod.tsx')); +}) + +Deno.test('env loader should accept js files', async () => { + const plugin = env(); + assert(plugin.test.test('mod.js')); +}) + +Deno.test('env loader should accept jsx files', async () => { + const plugin = env(); + assert(plugin.test.test('mod.jsx')); +}) + +Deno.test('env loader should be accept HMR files', async () => { + const plugin = env(); + assert(plugin.acceptHMR); +}) + +Deno.test('env loader should replace env variables', async () => { + const plugin = env(); + const { code, loader } = await plugin.transform?.( + (new TextEncoder).encode('const start = {{TEST_ENV_VAR}};'), + 'mod.ts' + )! + assertEquals(code, 'const start = 1;') +})