This repository has been archived by the owner on Mar 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
87 lines (74 loc) · 2.38 KB
/
index.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
'use strict';
const fs = require('fs');
const path = require('path');
const fse = require('fs-extra');
const camelcase = require('camelcase');
const cosmiconfig = require('cosmiconfig');
const DEFAULT_CONFIG = {
moduleName: 'EnvVars',
vars: [
"^NODE_ENV$",
"^ELM_"
]
};
module.exports = async bundler => {
// set .env files vars
const NODE_ENV = process.env.NODE_ENV;
const dotenvPath = path.join(process.cwd(), '.env');
const dotenvFiles = [
`${dotenvPath}.${NODE_ENV}.local`,
`${dotenvPath}.${NODE_ENV}`,
// Don't include `.env.local` for `test` environment
// since normally you expect tests to produce the same
// results for everyone
NODE_ENV !== 'test' && `${dotenvPath}.local`,
dotenvPath
].filter(Boolean);
dotenvFiles.forEach(dotenvFile => {
if (fs.existsSync(dotenvFile)) {
require('dotenv').config({
path: dotenvFile
});
}
});
// load config
let config = DEFAULT_CONFIG;
const explorer = cosmiconfig('parcel-plugin-elm-env-vars');
const customConfig = await explorer.search();
if (customConfig && customConfig.config) {
config = Object.assign(config, customConfig.config);
}
// filter allowed vars
const varsRegex = new RegExp(config.vars.join('|'), 'i');
const foundVars =
Object.keys(process.env)
.filter(key => varsRegex.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
}, {}
);
// write
const splittedModuleName =
config.moduleName.split('.')
.filter((s) => s)
.map((p) => camelcase(p, { pascalCase: true }));
const middlePaths = splittedModuleName.slice(0, -1);
const fileName = splittedModuleName.slice(-1)[0];
const outputDir = path.join.apply(null, [process.cwd(), 'autogenerated'].concat(middlePaths));
await fse.outputFile(path.join(outputDir, `${fileName}.elm`), generateElmFileContent(splittedModuleName.join('.'), foundVars));
};
function generateElmFileContent(moduleName, foundVars) {
const envVars =
Object.entries(foundVars)
.map(([originalName, value]) => {
const funcName = camelcase(originalName);
return `\n${funcName} : String\n${funcName} =\n ${JSON.stringify(value)}\n`;
}).join('\n');
const content = `module ${moduleName} exposing (..)
-- This file was autogenerated by parcel-plugin-elm-env-vars.
-- Do not edit it manually.
${envVars}`
return content;
}