Skip to content

Commit

Permalink
refactor: prevent id being proceded.
Browse files Browse the repository at this point in the history
  • Loading branch information
iendeavor committed Jan 30, 2022
1 parent 9bd627d commit a43990b
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions packages/vite-plugin-runtime-config/src/index.ts
Expand Up @@ -4,6 +4,8 @@ import path from "path";

const createPlugin: () => Plugin = () => {
const name = "runtime-config";
const runtimeConfigId = ".env";
const resolvedRuntimeConfigId = "\0" + runtimeConfigId;

const uniqueId = Array(10)
.fill(null)
Expand All @@ -16,27 +18,28 @@ const createPlugin: () => Plugin = () => {

let config: ResolvedConfig;
const legacyFileNames: string[] = [];

return <Plugin>{
name,
configResolved(_config) {
config = _config;
},
resolveId(id) {
if (id === ".env") {
return id;
if (id === runtimeConfigId) {
return resolvedRuntimeConfigId;
}
},
load(id) {
if (config.command === "serve") {
if (id === "/" + ".env") {
if (id === "/" + resolvedRuntimeConfigId) {
const result = `export default ${JSON.stringify(config.env)}`;
return result;
}
} else {
if (id === ".env") {
if (id === resolvedRuntimeConfigId) {
this.emitFile({
type: "asset",
fileName: `${config.build.assetsDir}/.env.js`,
fileName: `${config.build.assetsDir}/${runtimeConfigId}.js`,
source: [
`// Generated by runtime config, you could swap this file to change env.`,
`// https://vitejs.dev/guide/env-and-mode.html#env-files`,
Expand All @@ -55,12 +58,12 @@ const createPlugin: () => Plugin = () => {
}
} else {
if (code.includes(uniqueId)) {
return `import ${uniqueId} from './.env.js';` + code;
return `import ${uniqueId} from './${runtimeConfigId}.js';` + code;
}

if (chunk.name === ".env") {
return [
`import env from ${JSON.stringify("./.env.js")};`,
`import env from ${JSON.stringify(`./${runtimeConfigId}.js`)};`,
`export default env`,
].join("\n");
}
Expand Down

0 comments on commit a43990b

Please sign in to comment.