Skip to content

Commit

Permalink
feat($config): add env config
Browse files Browse the repository at this point in the history
  • Loading branch information
iq9891 committed May 7, 2022
1 parent c38f3ed commit b8c087e
Show file tree
Hide file tree
Showing 28 changed files with 323 additions and 53 deletions.
4 changes: 3 additions & 1 deletion bugs.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
<!-- @format -->

# 问题修复记录

- FIX No.1 remote 的时候无法更新数据
[runtime-core.esm-bundler.js:4353] Feature flags __VUE_OPTIONS_API__, __VUE_PROD_DEVTOOLS__ are not explicitly defined. You are running the esm-bundler build of Vue, which expects these compile-time feature flags to be globally injected via the bundler config in order to get better tree-shaking in the production bundle.
[runtime-core.esm-bundler.js:4353] Feature flags **VUE_OPTIONS_API**, **VUE_PROD_DEVTOOLS** are not explicitly defined. You are running the esm-bundler build of Vue, which expects these compile-time feature flags to be globally injected via the bundler config in order to get better tree-shaking in the production bundle.
1 change: 1 addition & 0 deletions demos/env/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
BIU_SITE=https://site.com
1 change: 1 addition & 0 deletions demos/env/.env.dev
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
BIU_API=http://baidu.com
1 change: 1 addition & 0 deletions demos/env/.env.test
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
BIU_API=http://water-pro.com
5 changes: 5 additions & 0 deletions demos/env/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<!-- @format -->

# 环境变量

在根目录设置环境文件,如 **.env.dev** 。若改变环境变量,重启后没发现变化,可清除(`rm -rf node_modules/.biu-cache`)缓存再试。
13 changes: 13 additions & 0 deletions demos/env/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "env",
"description": "环境变量",
"scripts": {
"start": "biu dev -e dev"
},
"dependencies": {
"vue": "^3.2.31"
},
"devDependencies": {
"@fe6/biu": "workspace:*"
}
}
14 changes: 14 additions & 0 deletions demos/env/src/App.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!-- @format -->

<template>
<div>
<h1>接口(process.env.BIU_API): {{ nowApi }}</h1>
<h1>官网(process.env.BIU_SITE): {{ nowSite }}</h1>
</div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
const nowApi = ref(process.env.BIU_API);
const nowSite = ref(process.env.BIU_SITE);
</script>
6 changes: 6 additions & 0 deletions demos/env/src/bootstrap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/** @format */

import App from './App.vue';
import { createApp } from 'vue';

createApp(App).mount('#biu-root');
3 changes: 3 additions & 0 deletions demos/env/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/** @format */

import('./bootstrap');
11 changes: 11 additions & 0 deletions demos/env/src/shims-vue.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/** @format */

declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<
Record<string, never>,
Record<string, never>,
unknown
>;
export default component;
}
5 changes: 5 additions & 0 deletions demos/env/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": "@fe6/biu/biu-tsconfig.json",
"include": ["components.d.ts", "src"],
"exclude": ["node_modules"]
}
1 change: 1 addition & 0 deletions packages/biu/src/config/def-conf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export const mergeConfig = (opts: any = {}): TConfig => {
publicDir: 'public',
cacheDir: 'node_modules/.biu-cache',
build,
envPrefix: ['BIU_'],
define: [],
plugins: [],
server,
Expand Down
4 changes: 2 additions & 2 deletions packages/biu/src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
ENUM_ENV,
TOverride,
TEntries,
TMode,
TConfigDebug,
TConfigResolve,
} from '../types';
Expand All @@ -20,7 +19,7 @@ import { TWebpackChain } from './options/chain';

export interface IConfigEnv {
mode: ENUM_ENV;
env?: TMode;
env?: string;
[key: string]: any;
}

Expand Down Expand Up @@ -168,6 +167,7 @@ export type TConfig = TOverride<
webpackChain?: TWebpackChain;
reactRuntime?: 'automatic' | 'classic';
base?: string;
envPrefix: string[];
html: IHtmlOptions;
entries?: TEntries;
debug: TConfigDebug;
Expand Down
1 change: 1 addition & 0 deletions packages/biu/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ export {
IConfigEnv,
TConfig,
} from './config/types';
export { TMode } from './types';
export { TConfigPluginOptions } from './config/types';
export { default as biuStore } from './shared/cache';
4 changes: 2 additions & 2 deletions packages/biu/src/webpack/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class WPCommon {
}
return {
name: `${store.pkg.name || 'emp'}-${store.config.mode}-${
store.config.env || 'local'
store.cmdOpts.env || 'local'
}-${store.pkg.version}`,
type: 'filesystem',
cacheDirectory: store.cacheDir,
Expand Down Expand Up @@ -84,7 +84,7 @@ class WPCommon {
// module: true,
// dynamicImport: true,
};
const publicPath = store.config.base || '';
// const publicPath = store.config.base || '';
// const clean = true
const clean = {
keep(asset: string) {
Expand Down
92 changes: 47 additions & 45 deletions packages/biu/src/webpack/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,72 +1,74 @@
/** @format */

// import path from 'path';
import webpack from '@fe6/biu-deps-webpack/compiled/webpack';
// import Dotenv from '@fe6/biu-deps/compiled/dotenv-webpack';
import dotenv from '@fe6/biu-deps-webpack/compiled/dotenv';
import { expand as dotenvExpand } from '@fe6/biu-deps-webpack/compiled/dotenv-expand';
import fs from '@fe6/biu-deps/compiled/fs-extra';
import { logger } from '@fe6/biu-utils';
import wpChain from '../shared/wp-chain';
import store from '../shared/cache';
import { TMode } from '../types';
// 多线程 dts
import DTSPlugin from '../dts';

class WPPlugin {
isDev = true;
constructor() {}
// private get dotenv() {
// const env = store.config.env || store.config.mode;
// const options = {
// path: store.resolve(`.env${env ? '.' + env : ''}`),
// // path: './some.other.env', // load this now instead of the ones in '.env'
// safe: true, // load '.env.example' to verify the '.env' variables are all set. Can also be a string to a different file.
// allowEmptyValues: true, // allow empty variables (e.g. `FOO=`) (treat it as empty string, rather than missing)
// systemvars: true, // load all the predefined 'process.env' variables which will trump anything local per dotenv specs.
// silent: true, // hide any errors
// defaults: false, // load '.env.defaults' as the default values if empty.
// };
// return {
// plugin: Dotenv,
// args: [options],
// };
// }
private get define() {
type optionsType = { [key: string]: string | number | boolean | TMode };
// 合并 mode env 参数
let dlist: optionsType = {
mode: store.config.mode,
env: store.config.env || '',
};
// 合并 store.config.define
getDefines() {
const env = store.cmdOpts.env || store.config.mode || '';

const envFiles = [
/** mode local file */ `.env.${env}.local`,
/** mode file */ `.env.${env}`,
/** local file */ `.env.local`,
/** default file */ `.env`,
];

let theNowEnv: any = {};

for (const file of envFiles) {
const theEnvFile = store.resolve(file);
const hasEnv = fs.existsSync(theEnvFile);
if (hasEnv) {
const parsed = dotenv.parse(fs.readFileSync(theEnvFile, 'utf-8'));
dotenvExpand({
parsed,
ignoreProcessEnv: true,
} as any);

for (const [key, value] of Object.entries(parsed)) {
if (
store.config.envPrefix.some((prefix: string) =>
key.startsWith(prefix),
) &&
theNowEnv[key] === undefined
) {
theNowEnv[key] = value;
}
}
}
}
if (store.config.define) {
dlist = { ...dlist, ...store.config.define };
theNowEnv = { ...theNowEnv, ...store.config.define };
}
//
const options: optionsType = {};
Object.keys(dlist).map((key) => {
if (store.isESM && store.config.useImportMeta) {
options[`import.meta.env.${key}`] = JSON.stringify(dlist[key]);
} else {
options[`process.env.${key}`] = JSON.stringify(dlist[key]);
}
});
// return defines
return {
plugin: webpack.DefinePlugin,
args: [options],
};
return theNowEnv;
}
//
async setup() {
const isDev = store.config.mode === 'development';
this.isDev = isDev;
const { define } = this; //, dotenv
const config: any = {
plugin: {
define,
// dotenv,
define: {
plugin: webpack.DefinePlugin,
args: [
{
'process.env': JSON.stringify(this.getDefines()),
},
],
},
},
};

if (Object.keys(store.biuShare.moduleFederation).length > 0) {
config.plugin.mf = {
plugin: webpack.container.ModuleFederationPlugin,
Expand Down
24 changes: 24 additions & 0 deletions packages/deps-webpack/compiled/dotenv-expand/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
Copyright (c) 2016, Scott Motte
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

29 changes: 29 additions & 0 deletions packages/deps-webpack/compiled/dotenv-expand/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// TypeScript Version: 3.0
/// <reference types="node" />

export interface DotenvExpandOptions {
ignoreProcessEnv?: boolean;
error?: Error;
parsed?: {
[name: string]: string;
}
}

export interface DotenvExpandOutput {
ignoreProcessEnv?: boolean;
error?: Error;
parsed?: {
[name: string]: string;
};
}

/**
* Adds variable expansion on top of dotenv.
*
* See https://docs.dotenv.org
*
* @param options - additional options. example: `{ ignoreProcessEnv: false, error: null, parsed: { { KEY: 'value' } }`
* @returns an object with a `parsed` key if successful or `error` key if an error occurred. example: { parsed: { KEY: 'value' } }
*
*/
export function expand(options?: DotenvExpandOptions): DotenvExpandOutput
1 change: 1 addition & 0 deletions packages/deps-webpack/compiled/dotenv-expand/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/deps-webpack/compiled/dotenv-expand/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"dotenv-expand","version":"8.0.3","author":"motdotla","license":"BSD-2-Clause","types":"lib/main.d.ts"}
23 changes: 23 additions & 0 deletions packages/deps-webpack/compiled/dotenv/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
Copyright (c) 2015, Scott Motte
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Loading

0 comments on commit b8c087e

Please sign in to comment.