Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit cf9a040

Browse files
committedJun 16, 2020
add prettier and format
1 parent 0da0e52 commit cf9a040

21 files changed

+262
-226
lines changed
 

‎.eslintrc.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,12 @@ module.exports = {
33
env: {
44
node: true
55
},
6-
extends: ["plugin:vue/essential", "@vue/prettier"],
6+
extends: ['plugin:vue/essential', '@vue/prettier'],
77
rules: {
8-
"no-console": process.env.NODE_ENV === "production" ? "error" : "off",
9-
"no-debugger": process.env.NODE_ENV === "production" ? "error" : "off"
8+
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
9+
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
1010
},
1111
parserOptions: {
12-
parser: "babel-eslint"
12+
parser: 'babel-eslint'
1313
}
14-
};
14+
}

‎.gitignore

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ yarn-error.log*
1313

1414
# Editor directories and files
1515
.idea
16-
.vscode
1716
*.suo
1817
*.ntvs*
1918
*.njsproj

‎.prettierrc

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"semi": false,
3+
"singleQuote": true,
4+
"printWidth": 80,
5+
"tabWidth": 2,
6+
"useTabs": false,
7+
"trailingComma": "none"
8+
}

‎.vscode/settings.json

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
{
2+
// 编辑器保存自动格式化
3+
"editor.formatOnSave": true,
4+
// 锁紧字符
5+
"editor.tabSize": 2,
6+
// 自动在vscode顶部显示文件路径
7+
"window.title": "${dirty}${activeEditorMedium}${separator}${rootName}",
8+
// 搜索排除
9+
"search.exclude": {
10+
"**/node_modules": true,
11+
"**/bower_components": true,
12+
"**/dist": true
13+
},
14+
// 控制是否在搜索中跟踪符号链接,会导致cpu内存占有率过高
15+
"search.followSymlinks": false,
16+
// 自动fetch远程分支
17+
"git.autofetch": true,
18+
// eslint开启
19+
"eslint.enable": true,
20+
// eslint自动保存格式话
21+
"editor.codeActionsOnSave": {
22+
"source.fixAll.eslint": true
23+
},
24+
// 保存超时时长
25+
"editor.codeActionsOnSaveTimeout": 2500,
26+
// 依赖prettier配置文件来格式化
27+
"prettier.requireConfig": true
28+
}

‎babel.config.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
module.exports = {
2-
presets: ["@vue/app"]
3-
};
2+
presets: ['@vue/app']
3+
}

‎postcss.config.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@ module.exports = {
22
plugins: {
33
autoprefixer: {}
44
}
5-
};
5+
}

‎src/App.vue

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
<style lang="scss">
1111
#app {
12-
font-family: "Avenir", Helvetica, Arial, sans-serif;
12+
font-family: 'Avenir', Helvetica, Arial, sans-serif;
1313
-webkit-font-smoothing: antialiased;
1414
-moz-osx-font-smoothing: grayscale;
1515
text-align: center;

‎src/api/index.js

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,34 @@
1-
import axios from "axios";
2-
const TARGET_SERVER = process.env.VUE_ENV === "server";
1+
import axios from 'axios'
2+
const TARGET_SERVER = process.env.VUE_ENV === 'server'
33
// FOR PROXY TEST: const cnodeBaseUrl = TARGET_SERVER ? process.env.config.CNODE_HOST : "/feapi";
4-
const cnodeBaseUrl = process.env.config.CNODE_HOST;
4+
const cnodeBaseUrl = process.env.config.CNODE_HOST
55
export function fetchTopics({ cookies }) {
6-
return axios.get(cnodeBaseUrl + "/api/v1/topics", {
6+
return axios.get(cnodeBaseUrl + '/api/v1/topics', {
77
headers: getCommonHeader({ cookies })
8-
});
8+
})
99
}
1010

1111
export function fetchTopicDetail({ id, cookies }) {
1212
return axios.get(cnodeBaseUrl + `/api/v1/topic/${id}`, {
1313
headers: getCommonHeader({ cookies })
14-
});
14+
})
1515
}
1616

1717
function getCommonHeader({ cookies }) {
1818
if (TARGET_SERVER && cookies) {
19-
return { cookie: getCookieString(cookies) };
19+
return { cookie: getCookieString(cookies) }
2020
} else {
21-
return null;
21+
return null
2222
}
2323
}
2424

2525
function getCookieString(cookies) {
26-
let cookieStr = "";
26+
let cookieStr = ''
2727
for (var variable in cookies) {
28+
// eslint-disable-next-line no-prototype-builtins
2829
if (cookies.hasOwnProperty(variable)) {
29-
cookieStr += `${variable}=${encodeURIComponent(cookies[variable])}; `;
30+
cookieStr += `${variable}=${encodeURIComponent(cookies[variable])}; `
3031
}
3132
}
32-
return cookieStr;
33+
return cookieStr
3334
}

‎src/components/TopicItem.vue

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@
77

88
<script>
99
export default {
10-
name: "TopicItem",
10+
name: 'TopicItem',
1111
serverCacheKey: props => props.topicInfo.id, // for ssr cache item component
1212
props: {
1313
topicInfo: Object
1414
}
15-
};
15+
}
1616
</script>
1717

1818
<!-- Add "scoped" attribute to limit CSS to this component only -->

‎src/entry-client.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
import { createApp } from "./main";
2-
const { app, router, store } = createApp();
1+
import { createApp } from './main'
2+
const { app, router, store } = createApp()
33

44
// prime the store with server-initialized state.
55
// the state is determined during SSR and inlined in the page markup.
66
if (window.__INITIAL_STATE__) {
7-
store.replaceState(window.__INITIAL_STATE__);
7+
store.replaceState(window.__INITIAL_STATE__)
88
}
99
router.onReady(() => {
10-
app.$mount("#app");
11-
});
10+
app.$mount('#app')
11+
})

‎src/entry-server.js

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { createApp } from "./main";
1+
import { createApp } from './main'
22

33
// This exported function will be called by `bundleRenderer`.
44
// This is where we perform data-prefetching to determine the
@@ -7,10 +7,10 @@ import { createApp } from "./main";
77
// return a Promise that resolves to the app instance.
88
export default context => {
99
return new Promise((resolve, reject) => {
10-
const beginTime = Date.now();
11-
const { app, router, store } = createApp();
10+
const beginTime = Date.now()
11+
const { app, router, store } = createApp()
1212
// set router's location
13-
router.push(context.url);
13+
router.push(context.url)
1414
router.onReady(() => {
1515
// This `rendered` hook is called when the app has finished rendering
1616
context.rendered = () => {
@@ -19,11 +19,11 @@ export default context => {
1919
// When we attach the state to the context, and the `template` option
2020
// is used for the renderer, the state will automatically be
2121
// serialized and injected into the HTML as `window.__INITIAL_STATE__`.
22-
context.state = store.state;
22+
context.state = store.state
2323
/* eslint-disable-next-line */
2424
console.log(`[DATE] data pre-fetch: ${Date.now() - beginTime}ms url=${context.url}`);
25-
};
26-
resolve(app);
27-
}, reject);
28-
});
29-
};
25+
}
26+
resolve(app)
27+
}, reject)
28+
})
29+
}

‎src/main.js

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,56 @@
1-
import Vue from "vue";
2-
import App from "./App.vue";
3-
import { createRouter } from "./router";
4-
import { createStore } from "./store";
5-
import { sync } from "vuex-router-sync";
1+
import Vue from 'vue'
2+
import App from './App.vue'
3+
import { createRouter } from './router'
4+
import { createStore } from './store'
5+
import { sync } from 'vuex-router-sync'
66

77
//关闭生产模式下给出的提示
8-
Vue.config.productionTip = true;
8+
Vue.config.productionTip = true
99

1010
// for using vant components
11-
import Vant from "vant";
12-
import "vant/lib/index.css";
13-
Vue.use(Vant);
11+
import Vant from 'vant'
12+
import 'vant/lib/index.css'
13+
Vue.use(Vant)
1414
// global loading
1515
Vue.prototype.$loading = isLoading => {
1616
if (isLoading) {
1717
Vue.prototype.$toast.loading({
1818
mask: true,
19-
message: "加载中...",
19+
message: '加载中...',
2020
overlayStyle: {
21-
backgroundColor: "rgba(0, 0, 0, 0.1)"
21+
backgroundColor: 'rgba(0, 0, 0, 0.1)'
2222
},
2323
duration: 0
24-
});
24+
})
2525
} else {
26-
Vue.prototype.$toast.clear();
26+
Vue.prototype.$toast.clear()
2727
}
28-
};
28+
}
2929

3030
export function createApp() {
31-
const router = createRouter();
32-
const store = createStore();
31+
const router = createRouter()
32+
const store = createStore()
3333
// sync the router with the vuex store.
3434
// this registers `store.state.route`
35-
sync(store, router);
35+
sync(store, router)
3636
const app = new Vue({
3737
router,
3838
store,
3939
render: h => h(App)
40-
});
41-
return { app, router, store };
40+
})
41+
return { app, router, store }
4242
}
4343

4444
// promise.finally Polyfill
4545
if (!Promise.prototype.finally) {
4646
Promise.prototype.finally = function(callback) {
47-
let P = this.constructor;
47+
let P = this.constructor
4848
return this.then(
4949
value => P.resolve(callback()).then(() => value),
5050
reason =>
5151
P.resolve(callback()).then(() => {
52-
throw reason;
52+
throw reason
5353
})
54-
);
55-
};
54+
)
55+
}
5656
}

‎src/router/index.js

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
1-
import Vue from "vue";
2-
import Router from "vue-router";
3-
import Home from "../views/Home.vue";
1+
import Vue from 'vue'
2+
import Router from 'vue-router'
3+
import Home from '../views/Home.vue'
44

5-
Vue.use(Router);
5+
Vue.use(Router)
66

77
export function createRouter() {
88
return new Router({
9-
mode: "history",
9+
mode: 'history',
1010
routes: [
1111
{
12-
path: "/",
13-
name: "home",
12+
path: '/',
13+
name: 'home',
1414
component: Home
1515
},
1616
{
17-
path: "/detail/:id",
18-
name: "detail",
17+
path: '/detail/:id',
18+
name: 'detail',
1919
// route level code-splitting
2020
// this generates a separate chunk (about.[hash].js) for this route
2121
// which is lazy-loaded when the route is visited.
2222
component: () =>
23-
import(/* webpackChunkName: "detail" */ "../views/Detail.vue")
23+
import(/* webpackChunkName: "detail" */ '../views/Detail.vue')
2424
}
2525
]
26-
});
26+
})
2727
}

‎src/store/actions.js

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
1-
import { fetchTopics, fetchTopicDetail } from "../api";
1+
import { fetchTopics, fetchTopicDetail } from '../api'
22

33
export default {
44
FETCH_TOPICS_LIST: ({ commit, state }, { cookies }) => {
55
return state.topicsList
66
? Promise.resolve()
77
: fetchTopics({ cookies }).then(res =>
8-
commit("SET_TOPICS_LIST", { list: res.data.data })
9-
);
8+
commit('SET_TOPICS_LIST', { list: res.data.data })
9+
)
1010
},
1111
FETCH_TOPIC_DETAIL: ({ commit }, { id, cookies }) => {
1212
return fetchTopicDetail({ id, cookies }).then(res =>
13-
commit("SET_TOPIC_DETAIL", { detail: res.data.data })
14-
);
13+
commit('SET_TOPIC_DETAIL', { detail: res.data.data })
14+
)
1515
}
16-
};
16+
}

‎src/store/getters.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@ export default {
22
// aboutInfo (state) {
33
// return state.pageAbout
44
// }
5-
};
5+
}

‎src/store/index.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
import Vue from "vue";
2-
import Vuex from "vuex";
3-
import actions from "./actions";
4-
import mutations from "./mutations";
5-
import getters from "./getters";
1+
import Vue from 'vue'
2+
import Vuex from 'vuex'
3+
import actions from './actions'
4+
import mutations from './mutations'
5+
import getters from './getters'
66

7-
Vue.use(Vuex);
7+
Vue.use(Vuex)
88

99
export function createStore() {
1010
return new Vuex.Store({
@@ -16,5 +16,5 @@ export function createStore() {
1616
mutations,
1717
actions,
1818
getters
19-
});
19+
})
2020
}

‎src/store/mutations.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
export default {
22
SET_TOPICS_LIST: (state, { list }) => {
3-
state.topicsList = list;
3+
state.topicsList = list
44
},
55
SET_TOPIC_DETAIL: (state, { detail }) => {
6-
state.topicDetail = detail;
6+
state.topicDetail = detail
77
}
8-
};
8+
}

‎src/utils/tdk.js

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
1-
const TARGET_NODE = process.env.VUE_ENV === "server";
1+
const TARGET_NODE = process.env.VUE_ENV === 'server'
22

33
function getTdk(vm) {
4-
const { tdk } = vm.$options;
4+
const { tdk } = vm.$options
55
if (tdk) {
6-
return tdk.call(vm);
6+
return tdk.call(vm)
77
}
88
}
99

1010
function updateTdk(vm, vdom) {
11-
const tdk = getTdk(vm);
12-
vdom.title = (tdk && tdk.title) || "SSR PAGE";
13-
vdom.description = (tdk && tdk.description) || "";
14-
vdom.keywords = (tdk && tdk.keywords) || "";
11+
const tdk = getTdk(vm)
12+
vdom.title = (tdk && tdk.title) || 'SSR PAGE'
13+
vdom.description = (tdk && tdk.description) || ''
14+
vdom.keywords = (tdk && tdk.keywords) || ''
1515
// for append more meta or link seo need
16-
vdom.ssrHeadAddInfo = (tdk && tdk.ssrHeadAddInfo) || "";
16+
vdom.ssrHeadAddInfo = (tdk && tdk.ssrHeadAddInfo) || ''
1717
}
1818

1919
function serverUpdateTdk() {
20-
updateTdk(this, this.$ssrContext);
20+
updateTdk(this, this.$ssrContext)
2121
}
2222

2323
function clientUpdateTdk() {
24-
updateTdk(this, document);
24+
updateTdk(this, document)
2525
}
2626

27-
export default (TARGET_NODE ? serverUpdateTdk : clientUpdateTdk);
27+
export default (TARGET_NODE ? serverUpdateTdk : clientUpdateTdk)

‎src/views/Detail.vue

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -12,84 +12,84 @@
1212
</div>
1313
</template>
1414
<script>
15-
import { mapState } from "vuex";
16-
import updateTdk from "../utils/tdk";
15+
import { mapState } from 'vuex'
16+
import updateTdk from '../utils/tdk'
1717
export default {
18-
name: "Detail",
18+
name: 'Detail',
1919
data() {
2020
return {
2121
pageIndex: -1,
2222
isMounted: false //for control not ssr render
23-
};
23+
}
2424
},
2525
computed: {
26-
...mapState(["topicDetail", "topicsList"])
26+
...mapState(['topicDetail', 'topicsList'])
2727
},
2828
tdk() {
2929
return {
3030
title: this.topicDetail && this.topicDetail.title
31-
};
31+
}
3232
},
3333
serverPrefetch() {
34-
return this.fetchData();
34+
return this.fetchData()
3535
},
3636
mounted() {
37-
this.isMounted = true;
38-
const alreadyIncremented = !!this.topicDetail;
37+
this.isMounted = true
38+
const alreadyIncremented = !!this.topicDetail
3939
if (!alreadyIncremented) {
40-
this.fetchData().then(this.fetchDataMounted());
40+
this.fetchData().then(this.fetchDataMounted())
4141
} else {
42-
this.fetchDataMounted();
42+
this.fetchDataMounted()
4343
}
4444
},
4545
beforeRouteUpdate(to, from, next) {
4646
// 一般建议路由变更采用计算属性或者store直接绑定
4747
// 特殊情况处理可以采用如下方案 重新注册数据返回处理
48-
this.fetchData().then(this.fetchDataMounted());
49-
next();
48+
this.fetchData().then(this.fetchDataMounted())
49+
next()
5050
},
5151
destroyed() {
52-
this.$store.commit("SET_TOPIC_DETAIL", { detail: null });
52+
this.$store.commit('SET_TOPIC_DETAIL', { detail: null })
5353
},
5454
methods: {
5555
// fetchData for client and server render
5656
fetchData() {
57-
this.$loading(true);
57+
this.$loading(true)
5858
return this.$store
59-
.dispatch("FETCH_TOPIC_DETAIL", {
59+
.dispatch('FETCH_TOPIC_DETAIL', {
6060
id: this.$route.params.id
6161
})
6262
.finally(() => {
63-
this.$loading(false);
64-
updateTdk.call(this);
65-
});
63+
this.$loading(false)
64+
updateTdk.call(this)
65+
})
6666
},
6767
// fetchData callback on mounted
6868
fetchDataMounted() {
69-
this.pageIndex = this._getCurrentIndexInList();
69+
this.pageIndex = this._getCurrentIndexInList()
7070
},
7171
next() {
72-
const itemIndex = this._getCurrentIndexInList();
72+
const itemIndex = this._getCurrentIndexInList()
7373
if (itemIndex > -1 && itemIndex < this.topicsList.length - 1) {
74-
const id = this.topicsList[itemIndex + 1].id;
75-
this.$router.push({ path: `/detail/${id}` });
74+
const id = this.topicsList[itemIndex + 1].id
75+
this.$router.push({ path: `/detail/${id}` })
7676
}
7777
},
7878
prev() {
79-
const itemIndex = this._getCurrentIndexInList();
79+
const itemIndex = this._getCurrentIndexInList()
8080
if (itemIndex > -1 && itemIndex > 0) {
81-
const id = this.topicsList[itemIndex - 1].id;
82-
this.$router.push({ path: `/detail/${id}` });
81+
const id = this.topicsList[itemIndex - 1].id
82+
this.$router.push({ path: `/detail/${id}` })
8383
}
8484
},
8585
_getCurrentIndexInList() {
86-
if (!this.topicsList) return undefined;
87-
const finds = this.topicsList.filter(i => i.id == this.$route.params.id);
88-
const itemIndex = finds.length ? this.topicsList.indexOf(finds[0]) : -1;
89-
return itemIndex;
86+
if (!this.topicsList) return undefined
87+
const finds = this.topicsList.filter(i => i.id == this.$route.params.id)
88+
const itemIndex = finds.length ? this.topicsList.indexOf(finds[0]) : -1
89+
return itemIndex
9090
}
9191
}
92-
};
92+
}
9393
</script>
9494
<style lang="scss" scoped>
9595
.detail-layout {

‎src/views/Home.vue

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -14,66 +14,66 @@
1414
</template>
1515

1616
<script>
17-
import { mapState } from "vuex";
18-
import TopicItem from "../components/TopicItem";
19-
import updateTdk from "../utils/tdk";
17+
import { mapState } from 'vuex'
18+
import TopicItem from '../components/TopicItem'
19+
import updateTdk from '../utils/tdk'
2020
export default {
21-
name: "home",
21+
name: 'home',
2222
components: { TopicItem },
2323
data() {
2424
return {
2525
isMounted: false //for control not ssr render
26-
};
26+
}
2727
},
2828
computed: {
29-
...mapState(["topicsList"])
29+
...mapState(['topicsList'])
3030
},
3131
tdk() {
3232
return {
33-
title: "话题列表: " + (this.topicsList && this.topicsList[0].title),
33+
title: '话题列表: ' + (this.topicsList && this.topicsList[0].title),
3434
description: `话题Desc: ${this.topicsList &&
3535
this.topicsList[0].title} 时间: ${this.topicsList &&
3636
this.topicsList[0].create_at}`,
3737
keywords: `话题keywords`,
3838
ssrHeadAddInfo: `<link rel="canonical" href="https://www.github.com">`
39-
};
39+
}
4040
},
4141
serverPrefetch() {
42-
return this.fetchData();
42+
return this.fetchData()
4343
},
4444
mounted() {
45-
this.isMounted = true;
46-
const alreadyIncremented = !!this.topicsList;
45+
this.isMounted = true
46+
const alreadyIncremented = !!this.topicsList
4747
if (!alreadyIncremented) {
48-
this.fetchData().then(this.fetchDataMounted());
48+
this.fetchData().then(this.fetchDataMounted())
4949
} else {
50-
this.fetchDataMounted();
50+
this.fetchDataMounted()
5151
}
5252
},
5353
methods: {
5454
// fetchData for client and server render
5555
fetchData() {
56-
this.$loading(true);
57-
const cookies = this.$ssrContext && this.$ssrContext.cookies;
56+
this.$loading(true)
57+
const cookies = this.$ssrContext && this.$ssrContext.cookies
5858
return this.$store
59-
.dispatch("FETCH_TOPICS_LIST", { cookies })
59+
.dispatch('FETCH_TOPICS_LIST', { cookies })
6060
.finally(() => {
61-
this.$loading(false);
62-
updateTdk.call(this);
63-
});
61+
this.$loading(false)
62+
updateTdk.call(this)
63+
})
6464
},
6565
// fetchData callback on mounted
6666
fetchDataMounted() {
6767
this.topicsList &&
6868
this.topicsList.forEach(item => {
69-
item.create_at = new Date(item.create_at).toDateString();
70-
});
69+
item.create_at = new Date(item.create_at).toDateString()
70+
})
7171
},
7272
navDetail(detail) {
73-
this.$router.push({ path: `/detail/${detail.id}` });
73+
this.$router.push({ path: `/detail/${detail.id}` })
7474
}
7575
}
76-
};
76+
}
7777
</script>
7878
<style lang="scss" scoped>
7979
.topics-list {

‎vue.config.js

Lines changed: 72 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
1-
const VueSSRServerPlugin = require("vue-server-renderer/server-plugin");
2-
const VueSSRClientPlugin = require("vue-server-renderer/client-plugin");
3-
const nodeExternals = require("webpack-node-externals");
4-
const webpack = require("webpack");
5-
const CopyWebpackPlugin = require("copy-webpack-plugin");
6-
const deployConfig = require("./config");
7-
const path = require("path");
8-
const resolve = file => path.resolve(__dirname, file);
9-
const TARGET_NODE = process.env.BUILD_TARGET === "node";
10-
const target = TARGET_NODE ? "server" : "client";
11-
const isDev = process.env.NODE_ENV && process.env.NODE_ENV.indexOf("dev") > -1;
1+
const VueSSRServerPlugin = require('vue-server-renderer/server-plugin')
2+
const VueSSRClientPlugin = require('vue-server-renderer/client-plugin')
3+
const nodeExternals = require('webpack-node-externals')
4+
const webpack = require('webpack')
5+
const CopyWebpackPlugin = require('copy-webpack-plugin')
6+
const deployConfig = require('./config')
7+
const path = require('path')
8+
const resolve = file => path.resolve(__dirname, file)
9+
const TARGET_NODE = process.env.BUILD_TARGET === 'node'
10+
const target = TARGET_NODE ? 'server' : 'client'
11+
const isDev = process.env.NODE_ENV && process.env.NODE_ENV.indexOf('dev') > -1
1212
module.exports = {
13-
publicPath: deployConfig[`${isDev ? "dev" : "build"}`].assetsPublicPath,
14-
assetsDir: "static",
13+
publicPath: deployConfig[`${isDev ? 'dev' : 'build'}`].assetsPublicPath,
14+
assetsDir: 'static',
1515
css: {
1616
sourceMap: !isDev && !TARGET_NODE // if enable sourceMap: fix ssr load Critical CSS throw replace of undefind
1717
},
1818
devServer: {
19-
headers: { "Access-Control-Allow-Origin": "*" },
19+
headers: { 'Access-Control-Allow-Origin': '*' },
2020
proxy: deployConfig.dev.proxyTable,
2121
disableHostCheck: true // 新增该配置项 fix ssr console error
2222
},
2323
transpileDependencies: [],
2424
// eslint-disable-next-line
2525
configureWebpack: config => ({
2626
entry: `./src/entry-${target}.js`,
27-
target: TARGET_NODE ? "node" : "web",
27+
target: TARGET_NODE ? 'node' : 'web',
2828
node: TARGET_NODE ? undefined : false,
2929
output: {
30-
libraryTarget: TARGET_NODE ? "commonjs2" : undefined
30+
libraryTarget: TARGET_NODE ? 'commonjs2' : undefined
3131
},
3232
// https://webpack.js.org/configuration/externals/#function
3333
// https://github.com/liady/webpack-node-externals
@@ -47,119 +47,119 @@ module.exports = {
4747
plugins: [
4848
TARGET_NODE ? new VueSSRServerPlugin() : new VueSSRClientPlugin(),
4949
new webpack.DefinePlugin({
50-
"process.env.VUE_ENV": `"${target}"`,
51-
"process.env.NODE_DEPLOY": `"${process.env.NODE_DEPLOY}"`,
52-
"process.env.config": getDeployConfigDefine()
50+
'process.env.VUE_ENV': `"${target}"`,
51+
'process.env.NODE_DEPLOY': `"${process.env.NODE_DEPLOY}"`,
52+
'process.env.config': getDeployConfigDefine()
5353
})
5454
].concat(
5555
isDev
5656
? []
5757
: new CopyWebpackPlugin([
5858
{
59-
from: resolve("./static"),
60-
to: resolve("./dist/static"),
61-
toType: "dir",
62-
ignore: ["index.html", ".DS_Store"]
59+
from: resolve('./static'),
60+
to: resolve('./dist/static'),
61+
toType: 'dir',
62+
ignore: ['index.html', '.DS_Store']
6363
},
6464
{
65-
from: resolve("./server"),
66-
to: resolve("./dist/server"),
67-
toType: "dir",
65+
from: resolve('./server'),
66+
to: resolve('./dist/server'),
67+
toType: 'dir',
6868
ignore: [
69-
"setup-dev-server.js",
70-
"pm2.config.template.js",
71-
".DS_Store"
69+
'setup-dev-server.js',
70+
'pm2.config.template.js',
71+
'.DS_Store'
7272
]
7373
},
7474
{
75-
from: resolve("./server/pm2.config.template.js"),
76-
to: resolve("./dist/server/pm2.config.js"),
75+
from: resolve('./server/pm2.config.template.js'),
76+
to: resolve('./dist/server/pm2.config.js'),
7777
transform: function(content) {
7878
return content
7979
.toString()
80-
.replace("NODE_ENV_VALUE", process.env.NODE_ENV)
81-
.replace("NODE_PORT_VALUE", process.env.NODE_PORT)
82-
.replace("NODE_DEPLOY_VALUE", process.env.NODE_DEPLOY);
80+
.replace('NODE_ENV_VALUE', process.env.NODE_ENV)
81+
.replace('NODE_PORT_VALUE', process.env.NODE_PORT)
82+
.replace('NODE_DEPLOY_VALUE', process.env.NODE_DEPLOY)
8383
}
8484
},
8585
{
86-
from: resolve("./package.json"),
87-
to: resolve("./dist")
86+
from: resolve('./package.json'),
87+
to: resolve('./dist')
8888
},
8989
{
90-
from: resolve("./package-lock.json"),
91-
to: resolve("./dist")
90+
from: resolve('./package-lock.json'),
91+
to: resolve('./dist')
9292
}
9393
])
9494
)
9595
}),
9696
chainWebpack: config => {
9797
// alias
9898
config.resolve.alias
99-
.set("@", resolve("src"))
100-
.set("@assets", resolve("src/assets"));
99+
.set('@', resolve('src'))
100+
.set('@assets', resolve('src/assets'))
101101

102102
// reset public/index.html to static/index.html
103-
config.plugin("html").tap(args => {
104-
args[0].template = resolve("./static/index.html");
105-
return args;
106-
});
103+
config.plugin('html').tap(args => {
104+
args[0].template = resolve('./static/index.html')
105+
return args
106+
})
107107

108108
if (TARGET_NODE) {
109109
// fix ssr bug: document not found -- https://github.com/Akryum/vue-cli-plugin-ssr/blob/master/lib/webpack.js
110-
const isExtracting = config.plugins.has("extract-css");
110+
const isExtracting = config.plugins.has('extract-css')
111111
if (isExtracting) {
112112
// Remove extract
113-
const langs = ["css", "postcss", "scss", "sass", "less", "stylus"];
114-
const types = ["vue-modules", "vue", "normal-modules", "normal"];
113+
const langs = ['css', 'postcss', 'scss', 'sass', 'less', 'stylus']
114+
const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
115115
for (const lang of langs) {
116116
for (const type of types) {
117-
const rule = config.module.rule(lang).oneOf(type);
118-
rule.uses.delete("extract-css-loader");
117+
const rule = config.module.rule(lang).oneOf(type)
118+
rule.uses.delete('extract-css-loader')
119119
// Critical CSS
120120
rule
121-
.use("vue-style")
122-
.loader("vue-style-loader")
123-
.before("css-loader");
121+
.use('vue-style')
122+
.loader('vue-style-loader')
123+
.before('css-loader')
124124
}
125125
}
126-
config.plugins.delete("extract-css");
126+
config.plugins.delete('extract-css')
127127
}
128128

129129
config.module
130-
.rule("vue")
131-
.use("cache-loader")
130+
.rule('vue')
131+
.use('cache-loader')
132132
.tap(options => {
133133
// Change cache directory for server-side
134-
options.cacheIdentifier += "-server";
135-
options.cacheDirectory += "-server";
136-
return options;
137-
});
134+
options.cacheIdentifier += '-server'
135+
options.cacheDirectory += '-server'
136+
return options
137+
})
138138
}
139139
config.module
140-
.rule("vue")
141-
.use("vue-loader")
140+
.rule('vue')
141+
.use('vue-loader')
142142
.tap(options => {
143143
if (TARGET_NODE) {
144-
options.cacheIdentifier += "-server";
145-
options.cacheDirectory += "-server";
144+
options.cacheIdentifier += '-server'
145+
options.cacheDirectory += '-server'
146146
}
147-
options.optimizeSSR = TARGET_NODE;
148-
return options;
149-
});
147+
options.optimizeSSR = TARGET_NODE
148+
return options
149+
})
150150

151151
// fix ssr hot update bug
152152
if (TARGET_NODE) {
153-
config.plugins.delete("hmr");
153+
config.plugins.delete('hmr')
154154
}
155155
}
156-
};
156+
}
157157

158158
// deploy config converter
159159
function getDeployConfigDefine() {
160-
let config = {};
160+
let config = {}
161161
Object.keys(deployConfig.env).forEach(function(key) {
162-
config[key] = `"${deployConfig.env[key]}"`;
163-
});
164-
return config;
162+
config[key] = `"${deployConfig.env[key]}"`
163+
})
164+
return config
165165
}

0 commit comments

Comments
 (0)
Please sign in to comment.