Skip to content

Commit

Permalink
feat: the production environment can be dynamically configured
Browse files Browse the repository at this point in the history
  • Loading branch information
vben-admin committed Oct 12, 2020
1 parent e83cb06 commit bb3b8f8
Show file tree
Hide file tree
Showing 29 changed files with 562 additions and 117 deletions.
4 changes: 4 additions & 0 deletions .env.production
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,7 @@ VITE_GLOB_API_URL=/api

# Interface prefix
VITE_GLOB_API_URL_PREFIX=


# TODO use Cdn
VITE_USE_CDN = true
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ yarn clean:lib # 删除node_modules,兼容window系统
- [x] 图表库
- [x] 数字动画
- [x] 首屏加载等待动画
- [x] 抽取生产环境配置文件

## 正在开发的功能

Expand All @@ -228,7 +229,7 @@ yarn clean:lib # 删除node_modules,兼容window系统
- [ ] 主题配置
- [ ] 黑暗主题
- [ ] 打包 Gzip
- [ ] 抽取生产环境配置文件
- [ ] 打包 CDN
- [ ] 系统性能优化

更多组件/功能/建议/bug/欢迎提交 pr 或者 issue
Expand Down
21 changes: 21 additions & 0 deletions build/config/vite/cdn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const css = ['//cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.min.css'];

// TODO use esm?
const js = [
'//cdn.bootcdn.net/ajax/libs/vue/3.0.0/vue.global.prod.js',
'//cdn.bootcdn.net/ajax/libs/vue-router/4.0.0-beta.13/vue-router.global.min.js',
'//cdn.bootcdn.net/ajax/libs/vuex/4.0.0-beta.4/vuex.global.prod.js',
'//cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.min.js',
'//cdn.bootcdn.net/ajax/libs/qs/6.9.4/qs.min.js',
'//cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.min.js',
// '//cdn.bootcdn.net/ajax/libs/lodash.js/4.17.15/lodash.min.js',
// '//cdn.bootcdn.net/ajax/libs/crypto-js/3.3.0/crypto-js.min.js',
// '//cdn.bootcdn.net/ajax/libs/vue-i18n/8.18.1/vue-i18n.min.js',
];

export const externals = ['vue', 'vuex', 'vue-router', 'axios', 'qs', 'nprogress'];

export const cdnConf = {
css,
js,
};
10 changes: 0 additions & 10 deletions build/config/vite/env.ts

This file was deleted.

1 change: 1 addition & 0 deletions build/constant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const GLOB_CONFIG_FILE_NAME = '_app.config.js';
5 changes: 5 additions & 0 deletions build/getShortName.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const getShortName = (env: any) => {
return `__PRODUCTION__${env.VITE_GLOB_APP_SHORT_NAME || '__APP'}__CONF__`
.toUpperCase()
.replace(/\s/g, '');
};
36 changes: 36 additions & 0 deletions build/jsc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// js调用cli 兼容调用ts

const { sh } = require('tasksfile');
const { argv } = require('yargs');

let command = ``;

Object.keys(argv).forEach((key) => {
if (!/^\$/.test(key) && key !== '_') {
// @ts-ignore
if (argv[key]) {
command += `--${key} `;
}
}
});

// 执行任务名称
let taskList = argv._;

let NODE_ENV = process.env.NODE_ENV || 'development';

if (taskList.includes('build') || taskList.includes('report') || taskList.includes('preview')) {
NODE_ENV = 'production';
}

if (taskList && Array.isArray(taskList) && taskList.length) {
sh(
`cross-env NODE_ENV=${NODE_ENV} ts-node --project ./build/tsconfig.json ./build/script/cli.ts ${taskList.join(
' '
)} ${command}`,
{
async: true,
nopipe: true,
}
);
}
28 changes: 28 additions & 0 deletions build/script/build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// #!/usr/bin/env node

import { sh } from 'tasksfile';
import { argv } from 'yargs';
import { runBuildConfig } from './buildConf';
import { runUpdateHtml } from './updateHtml';
import { errorConsole, successConsole } from '../utils';

export const runBuild = async () => {
try {
const argvList = argv._;
let cmd = `cross-env NODE_ENV=production vite build`;
await sh(cmd, {
async: true,
nopipe: true,
});

// Generate configuration file
if (!argvList.includes('no-conf')) {
await runBuildConfig();
}
await runUpdateHtml();
successConsole('Vite Build successfully!');
} catch (error) {
errorConsole('Vite Build Error\n' + error);
process.exit(1);
}
};
44 changes: 44 additions & 0 deletions build/script/buildConf.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { GLOB_CONFIG_FILE_NAME } from '../constant';
import fs, { writeFileSync } from 'fs-extra';

import viteConfig from '../../vite.config';
import { errorConsole, successConsole, getCwdPath, getEnvConfig } from '../utils';

const getShortName = (env: any) => {
return `__PRODUCTION__${env.VITE_GLOB_APP_SHORT_NAME || '__APP'}__CONF__`
.toUpperCase()
.replace(/\s/g, '');
};

function createConfig(
{
configName,
config,
configFileName = GLOB_CONFIG_FILE_NAME,
}: { configName: string; config: any; configFileName?: string } = { configName: '', config: {} }
) {
try {
const windowConf = `window.${configName}`;
const outDir = viteConfig.outDir || 'dist';
const configStr = `${windowConf}=${JSON.stringify(config)};
Object.freeze(${windowConf});
Object.defineProperty(window, "${configName}", {
configurable: false,
writable: false,
});
`;
fs.mkdirp(getCwdPath(outDir));
writeFileSync(getCwdPath(`${outDir}/${configFileName}`), configStr);

successConsole('The configuration file is build successfully!');
} catch (error) {
errorConsole('Configuration file configuration file failed to package\n' + error);
}
}

export function runBuildConfig() {
const config = getEnvConfig();
const configFileName = getShortName(config);
createConfig({ config, configName: configFileName });
}
24 changes: 5 additions & 19 deletions build/script/changelog.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
// #!/usr/bin/env node

import { sh } from 'tasksfile';
import chalk from 'chalk';
import { errorConsole, successConsole } from '../utils';

const createChangeLog = async () => {
export const runChangeLog = async () => {
try {
let cmd = `conventional-changelog -p custom-config -i CHANGELOG.md -s -r 0 `;
// if (shell.which('git')) {
// cmd += '&& git add CHANGELOG.md';
// }
await sh(cmd, {
async: true,
nopipe: true,
Expand All @@ -18,21 +15,10 @@ const createChangeLog = async () => {
async: true,
nopipe: true,
});
console.log(
chalk.blue.bold('**************** ') +
chalk.green.bold('CHANGE_LOG generated successfully!') +
chalk.blue.bold(' ****************')
);
successConsole('CHANGE_LOG.md generated successfully!');
} catch (error) {
console.log(
chalk.blue.red('**************** ') +
chalk.green.red('CHANGE_LOG generated error\n' + error) +
chalk.blue.red(' ****************')
);
errorConsole('CHANGE_LOG.md generated error\n' + error);

process.exit(1);
}
};
createChangeLog();
module.exports = {
createChangeLog,
};
45 changes: 45 additions & 0 deletions build/script/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#!/usr/bin/env node

import chalk from 'chalk';
import { argv } from 'yargs';

import { runChangeLog } from './changelog';
import { runPostInstall } from './postinstall';
import { runPreview } from './preview';
import { runPreserve } from './preserve';
import { runBuild } from './build';

const task = (argv._ || [])[0];

console.log('Run Task: ' + chalk.cyan(task));

switch (task) {
// change log
case 'log':
runChangeLog();
break;

case 'build':
runBuild();
break;

case 'preserve':
runPreserve();
break;

case 'postinstall':
runPostInstall();
break;

case 'preview':
runPreview();
break;

// TODO
case 'gzip':
break;
default:
break;
}

export default {};
12 changes: 12 additions & 0 deletions build/script/hm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// 百度统计代码 用于站点部署
// 只在build:site开启
export const hmScript = `<script>
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?384d6046e02f6ac4ea075357bd0e9b43";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script>
`;
11 changes: 8 additions & 3 deletions build/script/postinstall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@ import { exec, which } from 'shelljs';

function ignoreCaseGit() {
try {
if (which('git')) {
if (which('git').code === 0) {
exec('git config core.ignorecase false ');
}
} catch (error) {}
} catch (error) {
console.log(error);
}
}

export function runPostInstall() {
ignoreCaseGit();
}
ignoreCaseGit();
64 changes: 34 additions & 30 deletions build/script/preserve.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,57 @@
// 是否需要更新依赖,防止package.json更新了依赖,其他人获取代码后没有install
// Do you need to update the dependencies to prevent package.json from updating the dependencies, and no install after others get the code

import path from 'path';
import fs from 'fs-extra';
import { isEqual } from 'lodash';
import chalk from 'chalk';
import { sh } from 'tasksfile';
import { successConsole, errorConsole } from '../utils';

const resolve = (dir: string) => {
return path.resolve(process.cwd(), dir);
};

const reg = /[\u4E00-\u9FA5\uF900-\uFA2D]/;

let NEED_INSTALL = false;

fs.mkdirp(resolve('build/.cache'));
function checkPkgUpdate() {
const pkg = require('../../package.json');
const { dependencies, devDependencies } = pkg;
const depsFile = resolve('build/.cache/deps.json');
if (!fs.pathExistsSync(depsFile)) {
NEED_INSTALL = true;
return;
export async function runPreserve() {
const cwdPath = process.cwd();
if (reg.test(cwdPath)) {
errorConsole(
'Do not include Chinese, Japanese or Korean in the full path of the project directory, please modify the directory name and run again!'
);
errorConsole('项目目录全路径请勿包含中文、日文、韩文,请修改目录名后再次重新运行!');
process.exit(1);
}
const depsJson = require('../.cache/deps.json');

if (!isEqual(depsJson, { dependencies, devDependencies })) {
NEED_INSTALL = true;
}
}
checkPkgUpdate();
fs.mkdirp(resolve('build/.cache'));
function checkPkgUpdate() {
const pkg = require('../../package.json');
const { dependencies, devDependencies } = pkg;
const depsFile = resolve('build/.cache/deps.json');
if (!fs.pathExistsSync(depsFile)) {
NEED_INSTALL = true;
return;
}
const depsJson = require('../.cache/deps.json');

(async () => {
if (!isEqual(depsJson, { dependencies, devDependencies })) {
NEED_INSTALL = true;
}
}
checkPkgUpdate();
if (NEED_INSTALL) {
console.log(
chalk.blue.bold('**************** ') +
chalk.red.bold('检测到依赖变化,正在安装依赖(Tip: 项目首次运行也会执行)!') +
chalk.blue.bold(' ****************')
// no error
successConsole(
'A dependency change is detected, and the dependency is being installed to ensure that the dependency is consistent! (Tip: The project will be executed for the first time)!'
);
try {
// 从代码执行貌似不会自动读取.npmrc 所以手动加上源地址
// await run('yarn install --registry=https://registry.npm.taobao.org ', {
await sh('yarn install ', {
await sh('npm run bootstrap ', {
async: true,
nopipe: true,
});
console.log(
chalk.blue.bold('**************** ') +
chalk.green.bold('依赖安装成功,正在运行!') +
chalk.blue.bold(' ****************')
);

successConsole('Dependency installation is successful, start running the project!');

const pkg = require('../../package.json');
const { dependencies, devDependencies } = pkg;
Expand All @@ -64,4 +68,4 @@ checkPkgUpdate();
}
} catch (error) {}
}
})();
}
Loading

0 comments on commit bb3b8f8

Please sign in to comment.