Browse Source

使用 DefinePlugin 定义前端全局变量

master
巴林闲侠 2 years ago
parent
commit
74cd4280c6
  1. 48
      web/client/index.ejs
  2. 72
      web/client/index.html
  3. 16
      web/client/src/components/Upload/index.js
  4. 17
      web/client/src/layout/actions/global.js
  5. 39
      web/client/src/layout/actions/labour.js
  6. 23
      web/client/src/layout/actions/metting.js
  7. 23
      web/client/src/layout/actions/site.js
  8. 11
      web/client/src/layout/containers/layout/index.js
  9. 3
      web/client/src/layout/index.js
  10. 56
      web/client/src/layout/reducers/global.js
  11. 1
      web/client/src/utils/webapi.js
  12. 38
      web/config.js
  13. 69
      web/middlewares/webpack-dev.js
  14. 11
      web/routes/attachment/index.js
  15. 9
      web/webpack.config.js
  16. 3
      web/webpack.config.prod.js

48
web/client/index.ejs

@ -1,45 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" href="/assets/images/logo.png">
<link rel="stylesheet" type="text/css" href="/assets/font_sc/iconfont.css">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" href="/assets/images/logo.png">
<link rel="stylesheet" type="text/css" href="/assets/font_sc/iconfont.css">
</head>
<style>
<script type="text/javascript">
window._AMapSecurityConfig = {
securityJsCode: 'c50ace7f5825644b0905ee265360491b',
}
</script>
<script
src="https://webapi.amap.com/maps?v=2.0&key=0a0ee6a6589803fee75a4cf6a0c35df0&plugin=AMap.Adaptor,AMap.Scale,AMap.ToolBar,AMap.DistrictSearch,AMap.Geocoder,AMap.CustomLayer"></script>
<script src="https://webapi.amap.com/loca?v=2.0.0&key=26c2550b67c7d4730573a8ab02051d61"></script>
<script src="https://webapi.amap.com/ui/1.1/main.js?v=1.1.1"></script>
<script src="https://api.map.baidu.com/api?v=2.0&ak=wEiighBCdHAkOrXRHDsqlgW5"></script>
</head>
<style>
.amap-logo {
display: none;
opacity: 0 !important;
}
</style>
.amap-copyright {
opacity: 0;
}
@font-face {
font-family: YouSheBiaoTiHei;
src: url("/assets/font_sc/YouSheBiaoTiHei-2.ttf");
}
@font-face {
font-family: D-DIN;
src: url("/assets/font_sc/D-DIN.ttf");
}
</style>
<body style="background: transparent">
<div id='App'></div>
</body>
<body style="background: transparent">
<div id='App'></div>
</body>
</html>

72
web/client/index.html

@ -1,70 +1,20 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="shortcut icon" href="/assets/images/logo.png">
<link rel="stylesheet" type="text/css" href="/assets/font_sc/iconfont.css">
</head>
<style>
.amap-logo {
display: none;
opacity: 0 !important;
}
<head>
<meta charset="UTF-8">
<title></title>
<link rel="shortcut icon" href="/assets/images/logo.png">
<link rel="stylesheet" type="text/css" href="/assets/font_sc/iconfont.css">
</head>
<style>
.amap-copyright {
opacity: 0;
}
@font-face {
font-family: YouSheBiaoTiHei;
src: url("/assets/font_sc/YouSheBiaoTiHei-2.ttf");
}
@font-face {
font-family: SourceHanSansCN-Medium;
src: url("/assets/font_sc/SourceHanSansCN-Medium.otf");
}
@font-face {
font-family: SourceHanSansCN-Regular;
src: url("/assets/font_sc/SourceHanSansCN-Regular.otf");
}
@font-face {
font-family: D-DIN;
src: url("/assets/font_sc/D-DIN.ttf");
}
@font-face {
font-family: D-DIN-Bold;
src: url("/assets/font_sc/D-DIN-Bold.ttf");
}
</style>
<body>
<script type="text/javascript">
window._AMapSecurityConfig = {
securityJsCode: 'c50ace7f5825644b0905ee265360491b',
}
</script>
<script>
window.less = {
async: false,
env: 'production'
};
</script>
<script src="https://webapi.amap.com/maps?v=2.0&key=0a0ee6a6589803fee75a4cf6a0c35df0&plugin=AMap.Adaptor,AMap.Scale,AMap.ToolBar,AMap.DistrictSearch,AMap.Geocoder,AMap.CustomLayer"></script>
<script src="https://webapi.amap.com/ui/1.1/main.js?v=1.1.1"></script>
<script src="https://webapi.amap.com/loca?v=2.0.0&key=26c2550b67c7d4730573a8ab02051d61"></script>
<script src="https://api.map.baidu.com/api?v=2.0&ak=wEiighBCdHAkOrXRHDsqlgW5"></script>
</style>
<body>
<div id='App'></div>
<script type="text/javascript" src="http://localhost:5901/client/build/vendor.js"></script>
<script type="text/javascript" src="http://localhost:5901/client/build/app.js"></script>
<script type="text/javascript" src="http://localhost:5401/client/build/vendor.js"></script>
<script type="text/javascript" src="http://localhost:5401/client/build/app.js"></script>
</body>
</html>

16
web/client/src/components/Upload/index.js

@ -9,7 +9,7 @@ import { PlusOutlined, UploadOutlined, CloseOutlined } from '@ant-design/icons';
class Uploads extends Component {
constructor(props) {
super(props);
this.ApiRoot = localStorage.getItem('tyApiRoot')
this.ApiRoot = API_ROOT
this.state = {
fileUploading: false,
fileList: [],
@ -45,14 +45,14 @@ class Uploads extends Component {
// });
// };
componentDidMount() {
componentDidMount () {
const { value } = this.props;
if (value) {
this.setState(value);
}
}
componentWillReceiveProps(np) {
componentWillReceiveProps (np) {
const { dispatch, value: thisEditData, onChange } = this.props;
const { value: nextEditData } = np;
@ -99,7 +99,7 @@ class Uploads extends Component {
// }
}
render() {
render () {
const UploadPath = {
project: ['txt', 'dwg', 'doc', 'docx', 'xls', 'xlsx', 'pdf', 'png', 'jpg', 'rar', 'zip'],
report: ['doc', 'docx', 'xls', 'xlsx', 'pdf'],
@ -179,7 +179,7 @@ class Uploads extends Component {
onStateChange({ uploading: true });
}
},
onChange(info) {
onChange (info) {
const status = info.file.status;
if (status === 'uploading') {
that.setState({
@ -216,7 +216,7 @@ class Uploads extends Component {
}
}
},
onRemove(file) {
onRemove (file) {
let nextFileList = [];
fileList.map((f, i) => {
if (f.uid != file.uid) {
@ -235,7 +235,7 @@ class Uploads extends Component {
removeFilesList: nextRemoveFiles
});
},
onPreview(file) {
onPreview (file) {
let filePostfix = file.url.split('.').pop();
filePostfix = filePostfix.toLowerCase();
if (UploadPath.image.some((img) => img == filePostfix)) {
@ -306,7 +306,7 @@ class Uploads extends Component {
}
}
function mapStateToProps(state) {
function mapStateToProps (state) {
const { auth } = state
return {
user: auth.user

17
web/client/src/layout/actions/global.js

@ -25,20 +25,3 @@ export function resize (clientHeight, clientWidth) {
}
}
}
export const INIT_API_ROOT = 'INIT_API_ROOT';
export function initApiRoot () {
return dispatch => {
RouteRequest.get(RouteTable.apiRoot).then(res => {
localStorage.setItem('tyApiRoot', res.root);
localStorage.setItem('qnDomain', res.qiniu);
localStorage.setItem('aliAdmin', res.aliAdmin);
dispatch({
type: INIT_API_ROOT,
payload: {
apiRoot: res.root
}
})
});
}
}

39
web/client/src/layout/actions/labour.js

@ -1,39 +0,0 @@
'use strict';
import { ApiTable } from '$utils'
import { Request, basicAction } from '@peace/utils'
export const SET_GLOBAL_WORKER_LIST = 'SET_GLOBAL_WORKER_LIST';
export const CLEAR_GLOBAL_WORKER_LIST = 'CLEAR_GLOBAL_WORKER_LIST';
export function getWorkerList() {
return dispatch => {
Request.get(ApiTable.getWorkerList).then(res => {
dispatch({
type: SET_GLOBAL_WORKER_LIST,
payload: {
data: res
}
})
});
}
}
export const SET_GLOBAL_CHECK_LIST = 'SET_GLOBAL_CHECK_LIST';
export const CLEAR_GLOBAL_CHECK_LIST = 'CLEAR_GLOBAL_CHECK_LIST';
export function getCheckList() {
return dispatch => {
Request.get(ApiTable.getChcekList).then(res => {
dispatch({
type: SET_GLOBAL_CHECK_LIST,
payload: {
data: res
}
})
});
}
}
export default {
getWorkerList,
getCheckList
}

23
web/client/src/layout/actions/metting.js

@ -1,23 +0,0 @@
'use strict';
import { ApiTable } from '$utils'
import { Request, basicAction } from '@peace/utils'
export const SET_GLOBAL_METTING_LIST = 'SET_GLOBAL_METTING_LIST';
export const CLEAR_GLOBAL_METTING_LIST = 'CLEAR_GLOBAL_METTING_LIST';
export function getMettingList() {
return dispatch => {
Request.get(ApiTable.mettingList + '?state=已提交').then(res => {
dispatch({
type: SET_GLOBAL_METTING_LIST,
payload: {
data: res
}
})
});
}
}
export default {
getMettingList
}

23
web/client/src/layout/actions/site.js

@ -1,23 +0,0 @@
'use strict';
import { ApiTable } from '$utils'
import { Request, basicAction } from '@peace/utils'
export const SET_GLOBAL_SITE_LIST = 'SET_GLOBAL_SITE_LIST';
export const CLEAR_GLOBAL_SITE_LIST = 'CLEAR_GLOBAL_SITE_LIST';
export function getUserSiteList() {
return dispatch => {
Request.get(ApiTable.getUserSiteList).then(res => {
dispatch({
type: SET_GLOBAL_SITE_LIST,
payload: {
data: res
}
})
});
}
}
export default {
getUserSiteList
}

11
web/client/src/layout/containers/layout/index.js

@ -3,7 +3,7 @@
import './index.less';
import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { message, Layout, Breadcrumb, Badge } from 'antd';
import { message, Layout } from 'antd';
import Sider from '../../components/sider';
import Header from '../../components/header';
import Footer from '../../components/footer';
@ -11,7 +11,7 @@ import Breadcrumbs from './breadcrumb';
import { resize } from '../../actions/global';
import * as NProgress from 'nprogress';
import PerfectScrollbar from 'perfect-scrollbar';
import { getUserSiteList } from '../../actions/site';
NProgress.configure({
template: `
<div class="bar" style="height:2px" role="bar">
@ -22,12 +22,13 @@ NProgress.configure({
</div>
`
});
const headerHeight = 64
const footerHeight = 0
let scrollbar
const LayoutContainer = props => {
const { dispatch, msg, user, copyright, children, sections, clientWidth, clientHeight, location, match, routes, history, sites } = props
const { dispatch, msg, user, copyright, children, sections, clientWidth, clientHeight, location, match, routes, history } = props
const [collapsed, setCollapsed] = useState(false)
NProgress.start();
@ -43,9 +44,6 @@ const LayoutContainer = props => {
useEffect(() => {
resize_(collapsed)
scrollbar = new PerfectScrollbar('#page-content', { suppressScrollX: true });
if (!sites.length) {
dispatch(getUserSiteList());//获取工地列表
}
}, [])
useEffect(() => {
@ -128,7 +126,6 @@ function mapStateToProps (state) {
clientHeight: global.clientHeight,
msg: ajaxResponse.msg,
user: auth.user,
sites: global.sites
};
}

3
web/client/src/layout/index.js

@ -16,7 +16,7 @@ import 'antd/dist/antd.less';
moment.locale('zh-cn');
const { initLayout, initApiRoot } = layoutActions;
const { initLayout } = layoutActions;
const Root = props => {
const { sections, title, copyright } = props;
@ -124,7 +124,6 @@ const Root = props => {
let store = configStore(reducers, history);
store.dispatch(initLayout(title, copyright, sections, actions));
store.dispatch(actions.auth.initAuth());
store.dispatch(initApiRoot())
const combineRoutes = flatRoutes(innerRoutes);

56
web/client/src/layout/reducers/global.js

@ -1,10 +1,8 @@
'use strict';
import Immutable from 'immutable';
import { INIT_LAYOUT, RESIZE } from '../actions/global';
import { SET_GLOBAL_SITE_LIST, CLEAR_GLOBAL_SITE_LIST } from '../actions/site'
import { SET_GLOBAL_METTING_LIST, CLEAR_GLOBAL_METTING_LIST } from '../actions/metting'
import { SET_GLOBAL_WORKER_LIST, CLEAR_GLOBAL_WORKER_LIST, SET_GLOBAL_CHECK_LIST, CLEAR_GLOBAL_CHECK_LIST } from '../actions/labour'
function global(state = {
function global (state = {
title: '',
copyright: '',
sections: [],
@ -12,10 +10,6 @@ function global(state = {
plugins: {},
clientHeight: 768,
clientWidth: 1024,
sites: [],
metting: {},
worker: {},
check: {}
}, action) {
const payload = action.payload;
switch (action.type) {
@ -33,53 +27,7 @@ function global(state = {
plugins: payload.plugins,
clientHeight: state.clientHeight,
clientWidth: state.clientWidth,
detailsComponent: null,
sites: []
};
// case INIT_RESOURCE_ROOT:
// return Immutable.fromJS(state).merge(payload).toJS();
// case INIT_PAGE_HEADER_DETAILS:
// return Immutable.fromJS(state).merge({
// detailsComponent: payload.component
// }).toJS();
case SET_GLOBAL_SITE_LIST:
let list = payload.data;
let notRole3 = JSON.parse(sessionStorage.getItem('user')).role.type != 3;//非项目端用户
let singSiteId = sessionStorage.getItem('toggleSinglePlatformSiteId');//发生了跳转
if (notRole3 && singSiteId && window.location.href.indexOf('singleSiteBoard') != -1) {
list = payload.data.filter(s => s.id == singSiteId);//领导驾驶舱, 单工地跳转
}
return Immutable.fromJS(state).merge({
sites: list
}).toJS();
case CLEAR_GLOBAL_SITE_LIST:
return Immutable.fromJS(state).merge({
sites: []
}).toJS();
case SET_GLOBAL_METTING_LIST:
return Immutable.fromJS(state).merge({
metting: payload.data
}).toJS();
case CLEAR_GLOBAL_METTING_LIST:
return Immutable.fromJS(state).merge({
metting: {}
}).toJS();
case SET_GLOBAL_WORKER_LIST:
return Immutable.fromJS(state).merge({
worker: payload.data
}).toJS();
case CLEAR_GLOBAL_WORKER_LIST:
return Immutable.fromJS(state).merge({
worker: {}
}).toJS();
case SET_GLOBAL_CHECK_LIST:
return Immutable.fromJS(state).merge({
check: payload.data
}).toJS();
case CLEAR_GLOBAL_CHECK_LIST:
return Immutable.fromJS(state).merge({
check: {}
}).toJS();
default:
return state;
}

1
web/client/src/utils/webapi.js

@ -9,7 +9,6 @@ export const ApiTable = {
};
export const RouteTable = {
apiRoot: '/api/root',
fileUpload: '/_upload/new',
cleanUpUploadTrash: '/_upload/cleanup',
};

38
web/config.js

@ -28,6 +28,12 @@ const ANXINCLOUD_QINIU_SECRETKEY = process.env.ANXINCLOUD_QINIU_SECRETKEY || fla
const ANXINCLOUD_QINIU_BUCKET_RESOURCE = process.env.ANXINCLOUD_QINIU_BUCKET_RESOURCE || flags.qnbkt;
const ANXINCLOUD_QINIU_DOMAIN_QNDMN_RESOURCE = process.env.ANXINCLOUD_QINIU_DOMAIN_QNDMN_RESOURCE || flags.qndmn;
//阿里OSS
const ALI_OSS_ACCESSKEY = process.env.ALI_OSS_ACCESSKEY || flags.aliOssAccessKey;
const ALI_OSS_SECRETKET = process.env.ALI_OSS_SECRETKET || flags.aliOssSecretKey;
const ALI_OSS_BUCKET = process.env.ALI_OSS_BUCKET || flags.aliOssBucket;
const ALI_OSS_REGION = process.env.ALI_OSS_REGION || flags.aliOssRegion;
if (
!FS_UNIAPP_API
// || !ANXINCLOUD_QINIU_ACCESSKEY
@ -39,10 +45,13 @@ if (
args.showHelp();
process.exit(-1);
}
console.log(1,);
const product = {
port: flags.port || 8080,
staticDirs: [path.join(__dirname, './client')],
frontParams: {
API_ROOT: FS_UNIAPP_API
},
mws: [
{
entry: require('./middlewares/proxy').entry,
@ -64,6 +73,24 @@ const product = {
// uploadPath: 'other'
// }
// },
{
entry: require('./routes').entry,
opts: {
apiUrl: FS_UNIAPP_API,
staticRoot: './client',
qiniu: {
fetchUrl: '/_file-server',
domain: ANXINCLOUD_QINIU_DOMAIN_QNDMN_RESOURCE
},
aliOss: {
fetchUrl: '/_file-ali-server',
accessKey: ALI_OSS_ACCESSKEY,
secretKey: ALI_OSS_SECRETKET,
bucket: ALI_OSS_BUCKET,
region: ALI_OSS_REGION
}
}
},
{
entry: require('./client').entry,// 静态信息
opts: {}
@ -88,16 +115,20 @@ const product = {
maxRetries: 1
}
};
console.log(2, product);
let config;
if (dev) {
console.log(2.1);
config = {
port: product.port,
staticDirs: product.staticDirs,
frontParams: product.frontParams,
mws: product.mws.concat([
{
entry: require('./middlewares/webpack-dev').entry,
opts: {}
opts: {
frontParams: product.frontParams,
}
}
]),
logger: product.logger
@ -107,4 +138,5 @@ if (dev) {
config = product;
}
console.log(3, config);
module.exports = config;//区分开发和发布

69
web/middlewares/webpack-dev.js

@ -6,35 +6,48 @@ const middleware = require('webpack-dev-middleware');
const proxy = require('koa-better-http-proxy');
const url = require('url');
const compiler = webpack(devConfig);
module.exports = {
entry: function (app, router, opts) {
app.use(proxy('http://localhost:5901', {
filter: function (ctx) {
return /\/build/.test(url.parse(ctx.url).path);
},
proxyReqPathResolver: function (ctx) {
return 'client' + url.parse(ctx.url).path;
}
}));
entry: function (app, router, opts) {
devConfig.plugins.push(
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'),
...(() => {
let nextParams = {}
for (let k in opts.frontParams) {
nextParams[k] = JSON.stringify(opts.frontParams[k])
}
return nextParams
})()
}),
)
const compiler = webpack(devConfig);
app.use(proxy('http://localhost:5401', {
filter: function (ctx) {
return /\/build/.test(url.parse(ctx.url).path);
},
proxyReqPathResolver: function (ctx) {
return 'client' + url.parse(ctx.url).path;
}
}));
app.use(proxy('http://localhost:5901', {
filter: function (ctx) {
return /\/$/.test(url.parse(ctx.url).path);
},
proxyReqPathResolver: function (ctx) {
return 'client/build/index.html';
}
}));
app.use(proxy('http://localhost:5401', {
filter: function (ctx) {
return /\/$/.test(url.parse(ctx.url).path);
},
proxyReqPathResolver: function (ctx) {
return 'client/build/index.html';
}
}));
const server = express();
server.use(middleware(compiler));
//server.use(require("webpack-hot-middleware")(compiler));
server.listen('5901', function (err) {
if (err) {
console.log(err);
}
})
}
const server = express();
server.use(middleware(compiler));
//server.use(require("webpack-hot-middleware")(compiler));
server.listen('5401', function (err) {
if (err) {
console.log(err);
}
})
}
};

11
web/routes/attachment/index.js

@ -75,17 +75,6 @@ module.exports = {
await next();
}
};
const getApiRoot = async function (ctx) {
const { apiUrl, qiniu } = opts;
const { bucket, region } = opts.aliOss
ctx.status = 200;
ctx.body = {
root: apiUrl,
qiniu: qiniu.domain,
aliAdmin: `http://${bucket}.${region}.aliyuncs.com`
};
};
let upload = async function (ctx, next) {
try {

9
web/webpack.config.js

@ -6,7 +6,6 @@ const PATHS = {
app: path.join(__dirname, 'client/src'),
build: path.join(__dirname, 'client/build')
};
module.exports = {
mode: "development",
devtool: 'source-map',
@ -31,8 +30,14 @@ module.exports = {
}
},
plugins: [
// DefinePlugin 已在 middlewares 的 webpack-dev 中重新加载
// new webpack.DefinePlugin({
// 'process.env.NODE_ENV': JSON.stringify('development'),
// }),
new webpack.HotModuleReplacementPlugin(),
new BundleAnalyzerPlugin(),
new BundleAnalyzerPlugin({
analyzerPort: 8400,
}),
],
module: {
rules: [{

3
web/webpack.config.prod.js

@ -1,12 +1,13 @@
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const config = require('./config.js');
const PATHS = {
app: path.join(__dirname, 'client/src'),
build: path.join(__dirname, 'client/build')
};
console.log(config);
module.exports = {
mode: "production",
entry: {

Loading…
Cancel
Save