Skip to content

Commit

Permalink
feat: esbuild inject env
Browse files Browse the repository at this point in the history
  • Loading branch information
terwer committed Apr 14, 2023
1 parent daddd99 commit 420f7ac
Show file tree
Hide file tree
Showing 22 changed files with 234 additions and 35 deletions.
30 changes: 30 additions & 0 deletions apps/zhi-core/babel.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* Copyright (c) 2023, Terwer . All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Terwer designates this
* particular file as subject to the "Classpath" exception as provided
* by Terwer in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Terwer, Shenzhen, Guangdong, China, youweics@163.com
* or visit www.terwer.space if you need additional information or have any
* questions.
*/

const sharedConfig = require("jest-config-custom/babel.config.cjs")

module.exports = {
...sharedConfig,
}
28 changes: 28 additions & 0 deletions apps/zhi-core/env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* Copyright (c) 2023, Terwer . All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Terwer designates this
* particular file as subject to the "Classpath" exception as provided
* by Terwer in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Terwer, Shenzhen, Guangdong, China, youweics@163.com
* or visit www.terwer.space if you need additional information or have any
* questions.
*/

interface ImportMeta {
readonly env: ImportMetaEnv
}
2 changes: 1 addition & 1 deletion apps/zhi-core/esbuild.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const esbuildConfig: BuildOptions = {
entryPoints: ["src/index.ts"],
outfile: path.join(outDir, "theme.js"),
bundle: true,
format: "cjs",
format: "esm",
platform: "node",
plugins: [
dtsPlugin(),
Expand Down
3 changes: 2 additions & 1 deletion apps/zhi-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ import "./style/index.styl"
// const common = ZhiUtil.zhiCommon()

const zhi = new Zhi()
console.log("hello, zhi theme2345", zhi)
// console.log(import.meta.env)
console.log("hello, zhi theme", zhi)
// const zhi = new Zhi(common.deviceUtil.getDevice())
// await zhi.init()
})()
Expand Down
1 change: 1 addition & 0 deletions apps/zhi-env/.env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_DEBUG_MODE=true
1 change: 1 addition & 0 deletions apps/zhi-env/.env.development.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_DEBUG_MODE=true
1 change: 1 addition & 0 deletions apps/zhi-env/.env.production
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_DEBUG_MODE=false
1 change: 1 addition & 0 deletions apps/zhi-env/.env.production.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_DEBUG_MODE=false
1 change: 1 addition & 0 deletions apps/zhi-env/.env.test
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_DEBUG_MODE=true
1 change: 1 addition & 0 deletions apps/zhi-env/.env.test.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_DEBUG_MODE=true
24 changes: 14 additions & 10 deletions apps/zhi-env/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,21 @@ import Env from "zhi-env"
// https://github.com/vitejs/vite/issues/9539#issuecomment-1206301266
// 1 add modules:esnext to tsconfig.json
// 2 add env.d.ts
const envMeta = import.meta.env

const customEnv = {
[EnvConstants.NODE_ENV_KEY]: EnvConstants.NODE_ENV_DEVELOPMENT,
[EnvConstants.VITE_DEBUG_MODE_KEY]: false,
// [LogConstants.LOG_LEVEL_KEY]: LogLevelEnum.LOG_LEVEL_DEBUG,
// [LogConstants.LOG_PREFIX_KEY]: "zhi-common",
...envMeta,
}
// ```
// interface ImportMeta {
// readonly env: ImportMetaEnv
// }
// ```
// 3 add define to esbuild, vite etc.
// ```
// "import.meta.env": JSON.stringify({
// NODE_ENV: isWatch ? "development" : "production",
// ...getNormalizedEnvDefines(["NODE", "VITE_"]),
// })
// ```

const env = new Env(customEnv)
const envMeta = import.meta.env
const env = new Env(import.meta.env)

const val = env.getEnv("some-key")
console.log("val=>", val)
Expand Down
8 changes: 5 additions & 3 deletions apps/zhi-env/esbuild.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,16 @@ const outDir = path.join(baseDir, "dist")
// const baseDir = isWatch ? "my-custom-absolute-path" : "./"
// const outDir = isWatch ? baseDir : path.join(baseDir, "dist")

// console.log(process.env.VITE_DEBUG_MODE)

/**
* 构建配置
*/
export const esbuildConfig: BuildOptions = {
entryPoints: ["src/index.ts"],
outfile: path.join(outDir, "theme.js"),
outfile: path.join(outDir, "index.js"),
bundle: true,
format: "cjs",
format: "esm",
platform: "node",
plugins: [
dtsPlugin(),
Expand All @@ -71,4 +73,4 @@ export const esbuildConfig: BuildOptions = {
// watch: true,
// }),
],
}
}
15 changes: 8 additions & 7 deletions apps/zhi-env/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
"license": "GPL",
"keywords": [],
"scripts": {
"dev": "node --experimental-specifier-resolution=node --loader ts-node/esm scripts/build.ts --watch",
"build": "node --experimental-specifier-resolution=node --loader ts-node/esm scripts/build.ts --production",
"dev": "ts-node -T --esm --experimental-specifier-resolution=node scripts/build.ts --watch",
"build": "ts-node -T --esm --experimental-specifier-resolution=node scripts/build.ts --production",
"test": "jest",
"lint": "eslint \"src/**/*.{ts,js}\" --fix",
"doc": "../../packages/api-docs/node_modules/.bin/api-extractor run --local --verbose",
Expand All @@ -23,14 +23,15 @@
"devDependencies": {
"@types/minimist": "^1.2.2",
"@types/node": "^18.15.11",
"api-docs": "workspace:*",
"dotenv": "^16.0.3",
"esbuild": "^0.16.9",
"eslint-config-custom": "workspace:*",
"esbuild-plugin-d.ts": "^1.1.0",
"esbuild-plugin-copy": "^2.1.1",
"esbuild-plugin-d.ts": "^1.1.0",
"eslint-config-custom": "workspace:*",
"jest-config-custom": "workspace:*",
"minimist": "^1.2.8",
"ts-node": "^10.9.1",
"tsconfig": "workspace:*",
"api-docs": "workspace:*",
"jest-config-custom": "workspace:*"
"tsconfig": "workspace:*"
}
}
11 changes: 9 additions & 2 deletions apps/zhi-env/scripts/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import esbuild from "esbuild"
import { esbuildConfig } from "../esbuild.config"
import minimist from "minimist"
import { getNormalizedEnvDefines } from "./utils"

/**
* zhi 主题构建
Expand Down Expand Up @@ -87,10 +88,16 @@ class ZhiBuild {
if (!esbuildConfig.define) {
esbuildConfig.define = {}
}
esbuildConfig.define = {
const defineEnv = {
...esbuildConfig.define,
"process.env.NODE_ENV": isProduction ? '"production"' : '"development"',
...import.meta.env,
"import.meta.env": JSON.stringify({
NODE_ENV: isWatch ? "development" : "production",
...getNormalizedEnvDefines(["NODE", "VITE_"]),
}),
}
console.log("Detected env=>", defineEnv)
esbuildConfig.define = defineEnv

// hande result
const resultHandler = async (result: any) => {
Expand Down
71 changes: 71 additions & 0 deletions apps/zhi-env/scripts/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* Copyright (c) 2023, Terwer . All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Terwer designates this
* particular file as subject to the "Classpath" exception as provided
* by Terwer in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Terwer, Shenzhen, Guangdong, China, youweics@163.com
* or visit www.terwer.space if you need additional information or have any
* questions.
*/

import dotenv from "dotenv"

const loadDotenv = () => {
// try to use dotenv to load in custom local env vars to existing node runtime env vars:
// eslint-disable-next-line turbo/no-undeclared-env-vars
const envFile = process.env.NODE_ENV ? `.env.${process.env.NODE_ENV}` : ".env.production"
console.log(`loading env variables from ${envFile}`)
dotenv.config({ path: envFile })
}

/**
* 获取环境变量,仅构建工具使用
*
* @author terwer
* @version 0.1.0
* @since 0.1.0
*/
export const getNormalizedEnvDefines = (prefixes?: string[]): any => {
// load dotenv
loadDotenv()

// collect env
const envs = {
...import.meta.env,
} as any
for (let k in process.env) {
k = k.replace(/ /g, "") // hack for now.

// Bypass Windows errors
if (k === "CommonProgramFiles(x86)" || k === "ProgramFiles(x86)") {
continue
}

if (k.includes("NODE_PATH")) {
continue
}

if (prefixes && !prefixes.some((prefix) => k.startsWith(prefix))) {
continue
}

envs[`${k}`] = `${process.env[k]}`
}

return envs
}
15 changes: 11 additions & 4 deletions apps/zhi-env/src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,16 @@

import { describe, expect, it } from "@jest/globals"
import Env, { EnvConstants } from "./index"
import { getNormalizedEnvDefines } from "../scripts/utils"

describe("zhiEnv", () => {
const NOT_EXIST_KEY = "NOT_EXIST_KEY"
const defineEnv = getNormalizedEnvDefines()

it("test node env", () => {
const nodeEnv = import.meta.env.NODE_ENV
expect(nodeEnv).toEqual(EnvConstants.NODE_ENV_TEST)
})

it("test env", () => {
const env = new Env(import.meta.env)
Expand Down Expand Up @@ -60,23 +67,23 @@ describe("zhiEnv", () => {

const val = env.getStringEnv(EnvConstants.VITE_DEBUG_MODE_KEY)
console.log("val=>", val)
expect(val).toBeInstanceOf("string")
expect(typeof val).toBe("string")
})

it("test getBooleanEnv", function () {
const env = new Env(import.meta.env)

const val = env.getBooleanEnv(EnvConstants.VITE_DEBUG_MODE_KEY)
console.log("val=>", val)
expect(val).toBeInstanceOf("boolean")
expect(typeof val).toBe("boolean")
})

it("test getEnvOrDefault", function () {
const env = new Env(import.meta.env)

const val = env.getEnvOrDefault(NOT_EXIST_KEY, "hello")
console.log("val=>", val)
expect(val).toBeInstanceOf("string")
expect(typeof val).toBe("string")
})

it("test custom env", function () {
Expand All @@ -86,6 +93,6 @@ describe("zhiEnv", () => {

const val = env.getEnv("mykey-a")
console.log("val=>", val)
expect(val).toBeInstanceOf("string")
expect(typeof val).toBe("string")
})
})
5 changes: 5 additions & 0 deletions apps/zhi-env/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,10 @@

import EnvConstants from "./lib/EnvConstants"
import Env from "./lib/zhi-env"

console.log(import.meta.env)
const env = new Env(import.meta.env)
console.log(env.getEnv(EnvConstants.VITE_DEBUG_MODE_KEY))

export default Env
export { EnvConstants }
5 changes: 5 additions & 0 deletions apps/zhi-env/src/lib/EnvConstants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ class EnvConstants {
*/
public static NODE_ENV_PRODUCTION = "production"

/**
* 测试环境
*/
public static NODE_ENV_TEST = "test"

/**
* 是否处于调试模式
*/
Expand Down
2 changes: 1 addition & 1 deletion apps/zhi-env/src/lib/zhi-env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ class Env {
env = this.envMeta[key]
}
} catch (e: any) {
console.error(e)
// console.error(e)
}

return env
Expand Down
3 changes: 1 addition & 2 deletions packages/jest-config-custom/babel.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,5 @@
*/

module.exports = {
presets: [["@babel/preset-env", { targets: { node: "current" } }], "@babel/preset-typescript"],
plugins: ["babel-plugin-transform-vite-meta-env"],
presets: [["@babel/preset-env", { targets: { node: "current" } }], "@babel/preset-typescript","babel-preset-vite"],
}
2 changes: 1 addition & 1 deletion packages/jest-config-custom/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"@babel/preset-typescript": "^7.21.4",
"@types/jest": "^29.5.0",
"babel-jest": "^29.5.0",
"babel-plugin-transform-vite-meta-env": "^1.0.3",
"babel-preset-vite": "^1.1.0",
"jest": "^29.5.0",
"typescript": "^4.7.4"
}
Expand Down
Loading

0 comments on commit 420f7ac

Please sign in to comment.