Commit 4ec1d349 authored by 刘阳's avatar 刘阳

init

parents
[*.{js,jsx,ts,tsx,vue}]
indent_style = space
indent_size = 2
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 100
VUE_APP_API_HOST = ''
VUE_APP_API_HOST = ''
VUE_APP_API_HOST = ''
/public
/mock
/config/
/node_modules/
/*.js
module.exports = {
root: true,
env: {
node: true,
},
extends: [
'plugin:vue/vue3-essential',
],
parserOptions: {
ecmaVersion: 2020,
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'comma-dangle': 0,
'comma-spacing': 0, // 逗号前后的空格
'comma-style': [2, 'last'], // 逗号风格,换行时在行首还是行尾
quotes: [0, 'single'],
eqeqeq: 2,
'no-var': 1,
'key-spacing': [2, { beforeColon: false, afterColon: true }], // 对象字面量中冒号的前后空格
semi: 0,
'semi-spacing': [0, { before: false, after: true }], // 分号前后空格,
'use-isnan': 2, // 禁止比较时使用NaN,只能用isNaN()
'prefer-promise-reject-errors': 0,
'no-param-reassign': 0,
'no-unused-vars': 1,
'no-shadow': 0,
'import/extensions': 0,
'import/prefer-default-export': 0,
'eol-last': 0,
'no-unused-expressions': 0,
'no-underscore-dangle': 0,
'global-require': 0,
'no-new': 0,
'@typescript-eslint/no-explicit-any': ['off'],
},
overrides: [
{
files: ['**/__tests__/*.{j,t}s?(x)', '**/tests/unit/**/*.spec.{j,t}s?(x)'],
env: {
jest: true,
},
},
],
};
.DS_Store
node_modules
/dist
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
{{name}}
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# vue3tpl
## Project setup
```
yarn install
```
### Compiles and hot-reloads for development
```
yarn serve
```
### Compiles and minifies for production
```
yarn build
```
### Lints and fixes files
```
yarn lint
```
### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
]
}
const fs = require('fs')
const path = require('path');
const util = require('./util');
const dotenv = require('dotenv');
console.log("===============build config==================");
const BUILD_INFO = {
branch: process.env["npm_config_app_build_branch"] || '',
commit: process.env["npm_config_app_build_commit"] || '',
tag: process.env["npm_config_app_build_tag"] || '',
time: process.env["npm_config_app_build_time"] || '',
isAlert: process.env["npm_config_app_build_alert"] || false,
version: process.env["npm_config_app_version"] || ''
};
console.log(BUILD_INFO)
console.log('===============build config end==================')
const localEnv = path.join(__dirname, '..', '.env.local')
util.writeTxtToFile(`VUE_APP_BUILD_INFO=${JSON.stringify(BUILD_INFO)}`, localEnv)
const proxyUrl = 'http://192.168.32.30:3000'
const agentList = {
'/': {
target: proxyUrl,
}
}
module.exports = {
proxy: {
...agentList
},
publicPath: '/customTmplate-vue3',
outputDir: 'customTmplate-vue3'
}
\ No newline at end of file
const path = require('path')
const fs = require('fs')
const multiPages = () => {
const pagesPath = path.join(__dirname, '../src/pages')
const pages = {}
if(fs.existsSync(pagesPath)) {
const files = fs.readdirSync(pagesPath)
console.log(files)
files.forEach(item => {
const fileName = item.split('.')[0];
pages[fileName] = `src/pages/${fileName}/index.js`
})
} else {
return null
}
return pages
}
const configProxy = (proxy) => {
const uris = Object.keys(proxy)
const proxys = uris.map(uri => ({
[`${[uri]}`]: {
...proxy[uri],
bypass: (req, res) => {
res.header('x-target-url', (proxy[uri] || {}).target)
},
changeOrigin: true,
}
})).reduce((pre, current) => {
return {
...pre,
...current
}
}, {})
return proxys
}
const writeTxtToFile = (txt, file) => {
try {
fs.writeFileSync(file, txt, {
encoding: 'utf-8'
})
} catch (error) {
}
}
const readFile = (file) => {
if (fs.existsSync(file)) {
const data = fs.readFileSync(file, 'utf-8')
return data
}
return null
}
function resolve(dir) {
return path.join(__dirname, dir)
}
module.exports = {
multiPages,
configProxy,
writeTxtToFile,
readFile,
resolve
}
{
"name": "customTmplate-vue3",
"version": "0.1.0",
"description": "vue3模板",
"author": "liuy",
"private": true,
"scripts": {
"serve:dev": "vue-cli-service serve --mode development --fix",
"serve:stage": "vue-cli-service serve --mode stage",
"serve:prod": "vue-cli-service serve --mode production",
"build": "node config/dev.js && vue-cli-service build --report --mode production",
"build:stage": "node config/dev.js && vue-cli-service build --mode stage",
"dev": "npm run serve:dev",
"stage": "npm run serve:stage",
"prod": "npm run serve:prod",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.21.1",
"core-js": "^3.6.5",
"element-plus": "^1.0.2-beta.40",
"vue": "^3.0.0",
"vue-router": "^4.0.0-0",
"vuex": "^4.0.0-0"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^4.18.0",
"@typescript-eslint/parser": "^4.18.0",
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-plugin-router": "~4.5.0",
"@vue/cli-plugin-typescript": "~4.5.0",
"@vue/cli-plugin-vuex": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"@vue/compiler-sfc": "^3.0.0",
"@vue/eslint-config-standard": "^5.1.2",
"@vue/eslint-config-typescript": "^7.0.0",
"eslint": "^6.7.2",
"eslint-plugin-import": "^2.20.2",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.0",
"eslint-plugin-vue": "^7.0.0",
"node-sass": "^4.12.0",
"sass-loader": "^8.0.2",
"speed-measure-webpack-plugin": "^1.5.0",
"typescript": "~4.1.5"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"@vue/standard",
"@vue/typescript/recommended"
],
"parserOptions": {
"ecmaVersion": 2020
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
\ No newline at end of file
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
<% for (var i in htmlWebpackPlugin.options.cdn &&
htmlWebpackPlugin.options.cdn.scripts) { %>
<script type="text/javascript">
<%= htmlWebpackPlugin.options.cdn.scripts[i] %>
</script>
<% } %>
<% for (var i in htmlWebpackPlugin.options.cdn &&
htmlWebpackPlugin.options.cdn.js) { %>
<script type="text/javascript" src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script>
<% } %>
<% for (var i in htmlWebpackPlugin.options.cdn &&
htmlWebpackPlugin.options.cdn.css) { %>
<link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="stylesheet">
<% } %>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
<template>
<div id="app">
<g-header />
<div id="nav">
<router-link to="/">Home</router-link> |
</div>
<router-view/>
</div>
</template>
<script lang="ts">
import { Header } from '@/components'
export default {
components: {
GHeader: Header
}
}
</script>
<style lang='scss'>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
#nav {
padding: 30px;
}
#nav a {
font-weight: bold;
color: #2c3e50;
}
#nav a.router-link-exact-active {
color: #42b983;
}
</style>
body,ol,ul,h1,h2,h3,h4,h5,h6,p,th,td,dl,dd,form,
fieldset,legend,input,textarea, select {
margin: 0;
padding: 0;
}
p, span, div, body {
word-break:break-all;
-webkit-overflow-scrolling: touch;
}
\ No newline at end of file
.bordered {
border-top: solid 1px black;
}
@mixin ellipsis($num: 1) {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: $num;
-webkit-box-orient: vertical;
}
@mixin flexLayout($direction: row, $alignItems: center, $justc: flex-start) {
display: flex;
flex-flow: $direction;
justify-content: $justc;
align-items: $alignItems;
}
@font-face {
font-family: math-italic;
src: url('//public-1257124244.cos.ap-chengdu.myqcloud.com/plugins/latexfont/MathJax_Math-Italic.woff')
}
@font-face {
font-family: main-regular;
src: url('//public-1257124244.cos.ap-chengdu.myqcloud.com/plugins/latexfont/MathJax_Main-Regular.otf')
}
@function rpx($px) {
@return ($px / 750) * 100 + vw;
}
.content-option-math {
font-family: math-italic, main-regular;
}
figure {
max-width: 100px;
margin: 0;
vertical-align: middle;
text-align: center;
text-indent: 0;
img {
width: 100%;
margin: 5px;
text-indent: 0;
}
&.table {
text-align: center;
border-collapse: collapse;
border-spacing: 0;
& table td,
& table th {
min-width: 2em;
padding: .4em;
border: 1px solid #bfbfbf;
}
}
&+figure {
display: inline-table;
}
}
<template>
<div class="gk-header">
</div>
</template>
<style lang="scss" scoped>
.gk-header {
height: 64px;
width: 100%;
background-color: blue;
}
</style>
/* eslint-disable import/prefer-default-export */
import Header from './header/index.vue';
export {
Header,
};
export default {
}
\ No newline at end of file
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus';
import router from './router'
import store from './store'
import '@/utils/debug'
import '@/assets/styles/clear.scss'
import 'element-plus/lib/theme-chalk/index.css';
const app = createApp(App)
app.use(store)
app.use(router)
app.use(ElementPlus)
app.mount('#app')
app.config.performance = true
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import Home from '../views/Home.vue';
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: Home,
}
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
export default router;
/* eslint-disable */
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
/* eslint-disable */
import { createStore } from 'vuex';
const modules: {
[key: string]: any;
} = {};
const reqiureContext = require.context('./modules', false, /\.(js|ts)$/);
reqiureContext.keys().forEach((key) => {
const name = key.slice(2, -3); // 得到 state的名称
const moduleConfig = reqiureContext(key).default || reqiureContext(key);
modules[name] = {
...moduleConfig,
namespaced: true,
};
});
const store = createStore({
modules: {
...modules,
}
});
export default store
import { StoreOptions } from 'vuex';
export type HelloType = {
name: string;
age: string;
};
const hello: StoreOptions<HelloType> = {
state: {
name: 'sfsfs',
age: '7890',
},
mutations: {
changeName(state, payload) {
console.log(state, payload)
state.name = payload
}
},
actions: {
},
modules: {
}
};
export default hello;
import { ElMessageBox } from "element-plus";
const BUILD_INFO = process.env.VUE_APP_BUILD_INFO || "";
const info = BUILD_INFO && JSON.parse(BUILD_INFO);
if (info && info.isAlert === "true") {
ElMessageBox.alert(JSON.stringify(info), '');
}
import storage from './storage'
const isiOS = () => {
const u = navigator.userAgent
const iOs = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
return iOs;
}
const isAndroid = () => {
const u = navigator.userAgent
const android = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
return android
}
export default {
storage,
isiOS,
isAndroid
};
import axios from 'axios'
import storage from './storage'
const http = axios.create({
baseURL: process.env.NODE_ENV === 'production' ? '/' : '/api',
});
http.defaults.timeout = 10000;
// 响应拦截器
http.interceptors.response.use(
(response) => {
if (response.status >= 200 && response.status <= 299) {
const { data } = response;
if (data.code === 0) {
return Promise.resolve([data.data, null] as any);
}
return Promise.resolve([null, { code: data.code, msg: data.msg || '' }]);
}
return Promise.resolve([
null,
{ code: response.status, msg: '请求失败...' },
]);
},
(error) => {
if (error.response && error.response.status) {
return Promise.resolve([
null,
{ code: error.response.status, msg: '请求失败...' },
]);
}
return Promise.resolve([null, { code: 1000, msg: '请求失败...' }]);
}
);
http.interceptors.request.use(
(config) => {
// 设置token 或者 全局参数, headers等
config.headers = { 'Content-Type': 'application/json' };
const token = storage.getStorage('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(err) => Promise.reject(err)
);
/**
* 封装get方法
* @param url
* @param params
* @returns {Promise}
*/
export function get(api: string, params = {}): Promise<any> {
return http.get(api, { params });
}
/**
* 封装post请求
* @param url
* @param data
* @returns {Promise}
*/
export function post(api: string, data = {}): Promise<any> {
return http.post(api, data);
}
/**
* 封装patch请求
* @param url
* @param data
* @returns {Promise}
*/
export function patch(api: string, data = {}): Promise<any> {
return http.patch(api, data);
}
/**
* 封装put请求
* @param url
* @param data
* @returns {Promise}
*/
export function put(api: string, data = {}): Promise<any> {
return http.put(api, data);
}
export default http
/**
* 设置本地缓存
* @param {string} key
* @param {any} val
*/
function setStorage(key: string, val: any) {
localStorage.setItem(key, JSON.stringify(val))
}
/**
* 获取本地缓存
* @param {string} key
*/
function getStorage(key: string) {
const val = localStorage.getItem(key)
return val ? JSON.parse(val) : ''
}
/**
* 移除某一项缓存
* @param {string} key
*/
function removeStorage(key: string) {
localStorage.removeItem(key)
}
/**
* 清除所有缓存
*/
function clearStorage() {
localStorage.clear()
}
/**
* 设置本地临时缓存
* @param {string} key
* @param {any} val
*/
function setSession(key: string, val: any) {
sessionStorage.setItem(key, JSON.stringify(val))
}
/**
* 获取本地临时缓存
* @param {string} key
*/
function getSession(key: string) {
const val = sessionStorage.getItem(key)
return val ? JSON.parse(val) : ''
}
/**
* 移除某一项临时缓存
* @param {string} key
*/
function removeSession(key: string) {
sessionStorage.removeItem(key)
}
/**
* 清除所有临时缓存
*/
function clearSession() {
sessionStorage.clear()
}
export default {
setStorage,
getStorage,
clearStorage,
setSession,
getSession,
clearSession
}
<template>
<div class="home">
<img alt="Vue logo" src="@/assets/images/logo.png">
<p>{{ state.name }}</p>
<el-button type="primary" @click="update"> ss </el-button>
</div>
</template>
<script lang="ts">
import { computed, reactive, toRefs } from 'vue'
import { useStore } from 'vuex';
export default {
name: 'Home',
components: {
},
setup() {
const store = useStore()
const info = reactive({
nnn: '1232',
a: 242
})
const update = () => {
store.commit('hello/changeName', new Date().getTime())
}
const state = computed(() => store.state.hello)
return {
...toRefs(info),
state,
update,
}
}
}
</script>
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
// vue.config.js
const path = require('path');
const mock = require('./mock');
const config = require('./config');
const util = require('./config/util');
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const smp = new SpeedMeasurePlugin()
const configureWebpack = smp.wrap({
plugins: [],
externals: config.externals,
})
module.exports = {
configureWebpack,
chainWebpack: cfg => {
const cdn = config.cdn;
cfg.plugin("html").tap(args => {
args[0].cdn = cdn;
return args;
})
cfg.resolve.symlinks(true)
cfg.optimization.splitChunks(process.env.NODE_ENV === 'production' ? {
chunks: 'all',
minSize: 30000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 5,
maxInitialRequests: 5,
cacheGroups: {
element: {
test: /[\\/]node_modules[\\/]element-ui/,
name: 'chunk-element',
priority: -10 // 抽取优先级
},
vueGroup: {
test: /[\\/]node_modules[\\/]vue.*/,
name: 'chunk-vue',
priority: -10 // 抽取优先级
},
vendors: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
reuseExistingChunk: true,
priority: -20 // 抽取优先级
},
default: {
minChunks: 2,
priority: -20
}
}
} : {})
cfg.optimization.runtimeChunk({
name: entryPoint => `manifest.${entryPoint.name}`
})
},
css: {
loaderOptions: {
sass: {
prependData: `
@import "@/assets/styles/common.scss";
`
}
}
},
publicPath: config.publicPath || '/',
lintOnSave: true,
outputDir: config.outputDir,
pages: config.pages,
devServer: {
proxy: util.configProxy(config.proxy),
port: 3000,
open: true,
hot: true,
overlay: {
warnings: false,
errors: true
},
before(app) {
Object.keys(mock).forEach((key) => {
const mockValue = mock[key];
const result = typeof mockValue === 'function'
? mockValue
: (req, res) => res.json(mockValue);
if (/^(POST)./g.test(key)) {
app.post(`/api${key.replace('POST', '').trim()}`, result);
} else {
app.get(`/api${key.replace('GET', '').trim()}`, result);
}
});
}
}
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment