Commit 7b05dd2c by 尹烁恒

🎉 first init

parents
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": ["transform-runtime"],
"env": {
"test": {
"presets": ["env", "stage-2"],
"plugins": ["istanbul"]
}
}
}
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
build/*.js
config/*.js
// http://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: false,
node: true,
es6: true
},
// https://github.com/standard/standard/blob/master/docs/RULES-en.md
extends: 'standard',
// required to lint *.vue files
plugins: [
'html'
],
// add your custom rules here
'rules': {
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 0,
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
},
globals: {
App: true,
Page: true,
wx: true,
getApp: true,
getPage: true,
requirePlugin: true
}
}
.DS_Store
node_modules/
dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Editor directories and files
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
"plugins": {
"postcss-mpvue-wxss": {}
}
}
# mpvue_quickstart
> A Mpvue project
## Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
```
For detailed explanation on how things work, checkout the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
require('./check-versions')()
process.env.NODE_ENV = 'production'
var ora = require('ora')
var rm = require('rimraf')
var path = require('path')
var chalk = require('chalk')
var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf')
var spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot, '*'), err => {
if (err) throw err
webpack(webpackConfig, function (err, stats) {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
}
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})
var chalk = require('chalk')
var semver = require('semver')
var packageConfig = require('../package.json')
var shell = require('shelljs')
function exec (cmd) {
return require('child_process').execSync(cmd).toString().trim()
}
var versionRequirements = [
{
name: 'node',
currentVersion: semver.clean(process.version),
versionRequirement: packageConfig.engines.node
}
]
if (shell.which('npm')) {
versionRequirements.push({
name: 'npm',
currentVersion: exec('npm --version'),
versionRequirement: packageConfig.engines.npm
})
}
module.exports = function () {
var warnings = []
for (var i = 0; i < versionRequirements.length; i++) {
var mod = versionRequirements[i]
if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
warnings.push(mod.name + ': ' +
chalk.red(mod.currentVersion) + ' should be ' +
chalk.green(mod.versionRequirement)
)
}
}
if (warnings.length) {
console.log('')
console.log(chalk.yellow('To use this template, you must update following to modules:'))
console.log()
for (var i = 0; i < warnings.length; i++) {
var warning = warnings[i]
console.log(' ' + warning)
}
console.log()
process.exit(1)
}
}
/* eslint-disable */
require('eventsource-polyfill')
var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true')
hotClient.subscribe(function (event) {
if (event.action === 'reload') {
window.location.reload()
}
})
require('./check-versions')()
var config = require('../config')
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
}
// var opn = require('opn')
var path = require('path')
var express = require('express')
var webpack = require('webpack')
var proxyMiddleware = require('http-proxy-middleware')
var portfinder = require('portfinder')
var webpackConfig = require('./webpack.dev.conf')
// default port where dev server listens for incoming traffic
var port = process.env.PORT || config.dev.port
// automatically open browser, if not set will be false
var autoOpenBrowser = !!config.dev.autoOpenBrowser
// Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware
var proxyTable = config.dev.proxyTable
var app = express()
var compiler = webpack(webpackConfig)
// var devMiddleware = require('webpack-dev-middleware')(compiler, {
// publicPath: webpackConfig.output.publicPath,
// quiet: true
// })
// var hotMiddleware = require('webpack-hot-middleware')(compiler, {
// log: false,
// heartbeat: 2000
// })
// force page reload when html-webpack-plugin template changes
// compiler.plugin('compilation', function (compilation) {
// compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
// hotMiddleware.publish({ action: 'reload' })
// cb()
// })
// })
// proxy api requests
Object.keys(proxyTable).forEach(function (context) {
var options = proxyTable[context]
if (typeof options === 'string') {
options = { target: options }
}
app.use(proxyMiddleware(options.filter || context, options))
})
// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())
// serve webpack bundle output
// app.use(devMiddleware)
// enable hot-reload and state-preserving
// compilation error display
// app.use(hotMiddleware)
// serve pure static assets
var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
app.use(staticPath, express.static('./static'))
// var uri = 'http://localhost:' + port
var _resolve
var readyPromise = new Promise(resolve => {
_resolve = resolve
})
// console.log('> Starting dev server...')
// devMiddleware.waitUntilValid(() => {
// console.log('> Listening at ' + uri + '\n')
// // when env is testing, don't need open it
// if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
// opn(uri)
// }
// _resolve()
// })
module.exports = new Promise((resolve, reject) => {
portfinder.basePort = port
portfinder.getPortPromise()
.then(newPort => {
if (port !== newPort) {
console.log(`${port}端口被占用,开启新端口${newPort}`)
}
var server = app.listen(newPort, 'localhost')
// for 小程序的文件保存机制
require('webpack-dev-middleware-hard-disk')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true
})
resolve({
ready: readyPromise,
close: () => {
server.close()
}
})
}).catch(error => {
console.log('没有找到空闲端口,请打开任务管理器杀死进程端口再试', error)
})
})
var path = require('path')
var config = require('../config')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
exports.assetsPath = function (_path) {
var assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
return path.posix.join(assetsSubDirectory, _path)
}
exports.cssLoaders = function (options) {
options = options || {}
var cssLoader = {
loader: 'css-loader',
options: {
minimize: process.env.NODE_ENV === 'production',
sourceMap: options.sourceMap
}
}
var postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: true
}
}
var px2rpxLoader = {
loader: 'px2rpx-loader',
options: {
baseDpr: 1,
rpxUnit: 0.5
}
}
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
var loaders = [cssLoader, px2rpxLoader, postcssLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}
// https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
wxss: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }).concat({
loader: 'sass-resources-loader',
options: {
resources: path.resolve(__dirname, '../src/a ssets/mixin.scss')
}
}),
// add sass-resource-loader for mixin
scss: generateLoaders('sass').concat({
loader: 'sass-resources-loader',
options: {
resources: path.resolve(__dirname, '../src/assets/mixin.scss')
}
}),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}
// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
var output = []
var loaders = exports.cssLoaders(options)
for (var extension in loaders) {
var loader = loaders[extension]
output.push({
test: new RegExp('\\.' + extension + '$'),
use: loader
})
}
return output
}
var utils = require('./utils')
var config = require('../config')
// var isProduction = process.env.NODE_ENV === 'production'
// for mp
var isProduction = true
module.exports = {
loaders: utils.cssLoaders({
sourceMap: isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap,
extract: isProduction
}),
transformToRequire: {
video: 'src',
source: 'src',
img: 'src',
image: 'xlink:href'
}
}
var path = require('path')
var fs = require('fs')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
var MpvuePlugin = require('webpack-mpvue-asset-plugin')
var glob = require('glob')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
function getEntry (rootSrc, pattern) {
var files = glob.sync(path.resolve(rootSrc, pattern))
return files.reduce((res, file) => {
var info = path.parse(file)
var key = info.dir.slice(rootSrc.length + 1) + '/' + info.name
res[key] = path.resolve(file)
return res
}, {})
}
const appEntry = { app: resolve('./src/main.js') }
const pagesEntry = getEntry(resolve('./src'), 'pages/**/main.js')
const entry = Object.assign({}, appEntry, pagesEntry)
module.exports = {
// 如果要自定义生成的 dist 目录里面的文件路径,
// 可以将 entry 写成 {'toPath': 'fromPath'} 的形式,
// toPath 为相对于 dist 的路径, 例:index/demo,则生成的文件地址为 dist/index/demo.js
entry,
target: require('mpvue-webpack-target'),
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue': 'mpvue',
'@': resolve('src')
},
symlinks: false,
aliasFields: ['mpvue', 'weapp', 'browser'],
mainFields: ['browser', 'module', 'main']
},
module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.vue$/,
loader: 'mpvue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
include: [resolve('src'), resolve('test')],
use: [
'babel-loader',
{
loader: 'mpvue-loader',
options: {
checkMPEntry: true
}
},
]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name]].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[ext]')
}
}
]
},
plugins: [
new MpvuePlugin()
]
}
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
// var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// copy from ./webpack.prod.conf.js
var path = require('path')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
// add hot-reload related code to entry chunks
// Object.keys(baseWebpackConfig.entry).forEach(function (name) {
// baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
// })
module.exports = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.dev.cssSourceMap,
extract: true
})
},
// cheap-module-eval-source-map is faster for development
// devtool: '#cheap-module-eval-source-map',
devtool: '#source-map',
output: {
path: config.build.assetsRoot,
// filename: utils.assetsPath('js/[name].[chunkhash].js'),
// chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
filename: utils.assetsPath('js/[name].js'),
chunkFilename: utils.assetsPath('js/[id].js')
},
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
// copy from ./webpack.prod.conf.js
// extract css into its own file
new ExtractTextPlugin({
// filename: utils.assetsPath('css/[name].[contenthash].css')
filename: utils.assetsPath('css/[name].wxss')
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: {
safe: true
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module, count) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf('node_modules') >= 0
) || count > 1
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
chunks: ['vendor']
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
]),
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage
// new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
// new HtmlWebpackPlugin({
// filename: 'index.html',
// template: 'index.html',
// inject: true
// }),
new FriendlyErrorsPlugin()
]
})
var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var UglifyJsPlugin = require('uglifyjs-webpack-plugin')
var CopyWebpackPlugin = require('copy-webpack-plugin')
// var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
var env = config.build.env
var webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true
})
},
devtool: config.build.productionSourceMap ? '#source-map' : false,
output: {
path: config.build.assetsRoot,
// filename: utils.assetsPath('js/[name].[chunkhash].js'),
// chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
filename: utils.assetsPath('js/[name].js'),
chunkFilename: utils.assetsPath('js/[id].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
sourceMap: true
}),
// extract css into its own file
new ExtractTextPlugin({
// filename: utils.assetsPath('css/[name].[contenthash].css')
filename: utils.assetsPath('css/[name].wxss')
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: {
safe: true
}
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
// new HtmlWebpackPlugin({
// filename: config.build.index,
// template: 'index.html',
// inject: true,
// minify: {
// removeComments: true,
// collapseWhitespace: true,
// removeAttributeQuotes: true
// // more options:
// // https://github.com/kangax/html-minifier#options-quick-reference
// },
// // necessary to consistently work with multiple chunks via CommonsChunkPlugin
// chunksSortMode: 'dependency'
// }),
// keep module.id stable when vender modules does not change
new webpack.HashedModuleIdsPlugin(),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module, count) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf('node_modules') >= 0
) || count > 1
}
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
chunks: ['vendor']
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
// if (config.build.productionGzip) {
// var CompressionWebpackPlugin = require('compression-webpack-plugin')
// webpackConfig.plugins.push(
// new CompressionWebpackPlugin({
// asset: '[path].gz[query]',
// algorithm: 'gzip',
// test: new RegExp(
// '\\.(' +
// config.build.productionGzipExtensions.join('|') +
// ')$'
// ),
// threshold: 10240,
// minRatio: 0.8
// })
// )
// }
if (config.build.bundleAnalyzerReport) {
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
var merge = require('webpack-merge')
var prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})
// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: false,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8080,
// 在小程序开发者工具中不需要自动打开浏览器
autoOpenBrowser: false,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}
module.exports = {
NODE_ENV: '"production"'
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>mpvue_quickstart</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "mpvue_quickstart",
"version": "1.0.0",
"description": "A Mpvue project",
"author": "Eliaz <944126009@qq.com>",
"private": true,
"scripts": {
"dev": "node build/dev-server.js",
"start": "node build/dev-server.js",
"build": "node build/build.js",
"lint": "eslint --ext .js,.vue src"
},
"dependencies": {
"mpvue": "^1.0.11",
"node-sass": "^4.9.0",
"sass-loader": "^7.0.2",
"sass-resources-loader": "^1.3.3",
"vuex": "^3.0.1"
},
"devDependencies": {
"mpvue-loader": "^1.0.13",
"mpvue-webpack-target": "^1.0.0",
"mpvue-template-compiler": "^1.0.11",
"portfinder": "^1.0.13",
"postcss-mpvue-wxss": "^1.0.0",
"prettier": "~1.12.1",
"px2rpx-loader": "^0.1.10",
"babel-core": "^6.22.1",
"glob": "^7.1.2",
"webpack-mpvue-asset-plugin": "^0.0.2",
"babel-eslint": "^8.2.3",
"babel-loader": "^7.1.1",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-preset-env": "^1.3.2",
"babel-preset-stage-2": "^6.22.0",
"babel-register": "^6.22.0",
"chalk": "^2.4.0",
"connect-history-api-fallback": "^1.3.0",
"copy-webpack-plugin": "^4.5.1",
"css-loader": "^0.28.11",
"cssnano": "^3.10.0",
"eslint": "^4.19.1",
"eslint-friendly-formatter": "^4.0.1",
"eslint-loader": "^2.0.0",
"eslint-plugin-import": "^2.11.0",
"eslint-plugin-node": "^6.0.1",
"eslint-plugin-html": "^4.0.3",
"eslint-config-standard": "^11.0.0",
"eslint-plugin-promise": "^3.4.0",
"eslint-plugin-standard": "^3.0.1",
"eventsource-polyfill": "^0.9.6",
"express": "^4.16.3",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^1.1.11",
"friendly-errors-webpack-plugin": "^1.7.0",
"html-webpack-plugin": "^3.2.0",
"http-proxy-middleware": "^0.18.0",
"webpack-bundle-analyzer": "^2.2.1",
"semver": "^5.3.0",
"shelljs": "^0.8.1",
"uglifyjs-webpack-plugin": "^1.2.5",
"optimize-css-assets-webpack-plugin": "^3.2.0",
"ora": "^2.0.0",
"rimraf": "^2.6.0",
"url-loader": "^1.0.1",
"vue-style-loader": "^4.1.0",
"webpack": "^3.11.0",
"webpack-dev-middleware-hard-disk": "^1.12.0",
"webpack-merge": "^4.1.0",
"postcss-loader": "^2.1.4"
},
"engines": {
"node": ">= 4.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
{
"description": "项目配置文件。",
"setting": {
"urlCheck": true,
"es6": false,
"postcss": true,
"minified": true,
"newFeature": true
},
"miniprogramRoot": "./dist/",
"compileType": "miniprogram",
"appid": "wxa8fde6597493ec39",
"projectname": "mpvue_quickstart",
"condition": {
"search": {
"current": -1,
"list": []
},
"conversation": {
"current": -1,
"list": []
},
"game": {
"currentL": -1,
"list": []
},
"miniprogram": {
"current": -1,
"list": []
}
}
}
\ No newline at end of file
<script>
export default {
created () {
// 调用API从本地缓存中获取数据
const logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
console.log('app created and cache logs by setStorageSync')
}
}
</script>
<style lang="scss">
@import './assets/index.scss';
</style>
view {
box-sizing: border-box;
}
.white-shadow {
background: -webkit-linear-gradient(left, transparent, rgba(#fff, 0.5), transparent);
height: 6rpx;
}
button {
border: none;
&::after {
border: none;
}
}
@mixin ellipsis {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
<template>
<div>
<div class="card">
{{text}}
<p class="card-item" v-for="(item, subindex) in list" :key="subindex" @tap.stop="handleTap(subindex)">
{{item.id + 'item.id'}}
</p>
</div>
</div>
</template>
<script>
export default {
props: ['text', 'list'],
methods: {
handleTap (index) {
console.log('card.vue', index)
}
}
}
</script>
<style>
.card {
padding: 10px;
}
</style>
import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue(App)
app.$mount()
export default {
// 这个字段走 app.json
config: {
// 页面前带有 ^ 符号的,会被编译成首页,其他页面可以选填,我们会自动把 webpack entry 里面的入口页面加进去
pages: ['pages/logs/main', '^pages/index/main'],
window: {
backgroundTextStyle: 'light',
navigationBarBackgroundColor: '#fff',
navigationBarTitleText: 'WeChat',
navigationBarTextStyle: 'black'
},
debug: true
}
}
<template>
<div class="counter-warp">
<p>Vuex counter:{{ count }}</p>
<p>Vuex log: {{ log }}</p>
<p>
<button @click="increment">+</button>
<button @click="decrement">-</button>
</p>
<a href="/pages/index/main" class="home">去往首页</a>
</div>
</template>
<script>
// Use Vuex
import store from '@/store'
export default {
computed: {
count () {
return store.state.counterPage.count
},
log () {
return store.state.logPage.log
}
},
methods: {
increment () {
store.commit('increment')
},
decrement () {
store.commit('decrement')
}
}
}
</script>
<style>
.counter-warp {
text-align: center;
margin-top: 100px;
}
.home {
display: inline-block;
margin: 100px auto;
padding: 5px 10px;
color: blue;
border: 1px solid blue;
}
</style>
import Vue from 'vue'
import App from './index'
const app = new Vue(App)
app.$mount()
<template>
<div class="index-page">
</div>
</template>
<script>
export default {
onLoad () {
console.log(this.$root.$mp.query, this.$root.$mp.appOptions, this.$root.$mp)
},
onPageScroll () {
console.log('page is scroll')
},
beforeCreate () {
console.log('page is before create')
},
data () {
return {
userInfo: {}
}
},
components: {
card
},
methods: {
getUserInfo () {
wx.login({
success: () => {
wx.getUserInfo({
success: (res) => {
this.userInfo = res.userInfo
}
})
}
})
}
},
created () {
// 调用应用实例的方法获取全局数据
this.getUserInfo()
}
}
</script>
<style scoped lang="scss">
.index-page {
@include ellipsis;
}
</style>
import Vue from 'vue'
import App from './index'
const app = new Vue(App)
app.$mount()
// 这里才会导出json
export default {
config: {
navigationBarTitleText: '布里吉'
}
}
<template>
<div>
<ul class="container log-list">
<li v-for="(log, index) in logs" :class="{ red: aa }" :key="index" class="log-item">
<card :text="(index + 1) + ' . ' + log"></card>
</li>
</ul>
</div>
</template>
<script>
import { formatTime } from '@/utils/index'
import card from '@/components/card'
export default {
components: {
card
},
data () {
return {
logs: []
}
},
created () {
const logs = (wx.getStorageSync('logs') || [])
this.logs = logs.map(log => formatTime(new Date(log)))
}
}
</script>
<style>
.log-list {
display: flex;
flex-direction: column;
padding: 40rpx;
}
.log-item {
margin: 10rpx;
}
</style>
import Vue from 'vue'
import App from './index'
const app = new Vue(App)
app.$mount()
export default {
config: {
navigationBarTitleText: '查看启动日志'
}
}
// 鉴于wepy.request并没有axios的调用方式,故使用小程序环境的flyio
import Fly from 'flyio/dist/npm/wx'
const fly = new Fly()
let Authorization = null
function getAuthorization () {
return Authorization
}
function setAuthorization (header) {
Authorization = header
}
const log = console.log
fly.config.baseURL = ''
// add token
fly.interceptors.request.use((config, promise) => {
log(config, 'request config')
if (getAuthorization()) {
config.headers['Authorization'] = getAuthorization()
}
return config
})
fly.interceptors.response.use((config, promise) => {
if (config.headers['Authorization'.toLowerCase()]) {
setAuthorization(config.headers['Authorization'.toLowerCase()])
}
log(config, 'response')
return config
}, (error, promise) => {
log(error, 'response code error')
// 需要手动处理的错误类型(同后端的协议自处理返回码)
if (error.status === 422) {
// fly里面讲responseText存放在engine中.
let responseJSON = {}
try {
// responseJSON = JSON.parse(error.engine.responseText)
responseJSON = error.engine.response
} catch (error) {
log('JSON Parse error')
}
const response = {
error: 1,
errors: responseJSON.errors,
message: responseJSON.message
}
return promise.resolve({
data: response
})
} else if (error.status === 400) {
let response = error.engine.response
wx.showToast({
title: response.message,
icon: 'none',
duration: 2500
})
return promise.reject(error)
} else {
// 其他类型的错误直接reject掉
return promise.reject(error)
}
})
export default fly
// https://vuex.vuejs.org/zh-cn/intro.html
// make sure to call Vue.use(Vuex) if using a module system
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const counterModule = {
state: {
count: 0
},
mutations: {
increment: (state) => {
const obj = state
obj.count += 1
},
decrement: (state) => {
const obj = state
obj.count -= 1
}
}
}
const logsModule = {
state: {
log: 10
},
mutations: {
increment (state) {
state.log += 1
}
}
}
const store = new Vuex.Store({
modules: {
counterPage: counterModule,
logPage: logsModule
}
})
export default store
function formatNumber (n) {
const str = n.toString()
return str[1] ? str : `0${str}`
}
export function formatTime (date) {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
const t1 = [year, month, day].map(formatNumber).join('/')
const t2 = [hour, minute, second].map(formatNumber).join(':')
return `${t1} ${t2}`
}
export default {
formatNumber,
formatTime
}
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