Skip to content

Plugin env #77

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions plugins/env.ts
Original file line number Diff line number Diff line change
@@ -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;
38 changes: 38 additions & 0 deletions plugins/env_test.ts
Original file line number Diff line number Diff line change
@@ -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;')
})