├── .babelrc ├── .editorconfig ├── .eslintignore ├── .gitignore ├── .postcssrc.js ├── README.md ├── build ├── build.js ├── check-versions.js ├── dev-client.js ├── dev-server.js ├── utils.js ├── vue-loader.conf.js ├── webpack.base.conf.js ├── webpack.dev.conf.js └── webpack.prod.conf.js ├── config ├── dev.env.js ├── index.js └── prod.env.js ├── dev.md ├── index.html ├── package.json ├── project.config.json ├── src ├── App.vue ├── app.json ├── app.ts ├── components │ ├── card.vue │ ├── compb.ts │ └── compb.vue ├── data │ └── api.ts ├── index.d.ts ├── main.ts ├── packageA │ └── pages │ │ └── index │ │ ├── index.ts │ │ ├── index.vue │ │ ├── main.ts │ │ └── page.json ├── pages.js ├── pages │ ├── counter │ │ ├── counter.ts │ │ ├── index.vue │ │ ├── main.ts │ │ └── store.ts │ ├── index │ │ ├── index.less │ │ ├── index.ts │ │ ├── index.vue │ │ └── main.ts │ ├── logs │ │ ├── index.vue │ │ ├── main.json │ │ └── main.ts │ ├── page2 │ │ ├── index.vue │ │ └── main.ts │ └── testExtend │ │ ├── base.ts │ │ ├── index.ts │ │ ├── index.vue │ │ └── main.ts ├── utils │ ├── consts.ts │ ├── debug.js │ └── index.js └── vue-shim.d.ts ├── static └── .gitkeep ├── tsconfig.json ├── vendor ├── lodash.js └── lodash_export.js └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["env", { 4 | "modules": false, 5 | "targets": { 6 | "browsers": ["> 1%", "last 2 versions", "not ie <= 8"] 7 | } 8 | }], 9 | "stage-2" 10 | ], 11 | "plugins": ["transform-runtime", "transform-decorators-legacy"], 12 | "env": { 13 | "test": { 14 | "presets": ["env", "stage-2"], 15 | "plugins": ["istanbul"] 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | build/*.js 2 | config/*.js 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | dist/ 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Editor directories and files 9 | .idea 10 | *.suo 11 | *.ntvs* 12 | *.njsproj 13 | *.sln 14 | -------------------------------------------------------------------------------- /.postcssrc.js: -------------------------------------------------------------------------------- 1 | // https://github.com/michael-ciniawsky/postcss-load-config 2 | 3 | module.exports = { 4 | "plugins": { 5 | // to edit target browsers: use "browserslist" field in package.json 6 | "autoprefixer": {}, 7 | "postcss-mpvue-wxss": {} 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mpvue Typescript demo 2 | 3 | > A mpvue project with Typescript 4 | 5 | 已支持mpvue 2.0 (微信小程序、百度智能小程序、头条小程序、支付宝小程序) 6 | 7 | 1.x版本的请前往[v1](https://github.com/WingGao/mpvue-ts-demo/tree/v1)分支 8 | 9 | ## Build Setup 10 | 11 | ``` bash 12 | # install dependencies 13 | yarn 14 | 15 | # serve with hot reload at localhost:7100 16 | yarn run dev 17 | 18 | # build for production with minification 19 | yarn run build 20 | 21 | # build for production and view the bundle analyzer report 22 | yarn run build --report 23 | ``` 24 | 25 | 26 | [mpvue](https://github.com/Meituan-Dianping/mpvue) 27 | -------------------------------------------------------------------------------- /build/build.js: -------------------------------------------------------------------------------- 1 | require('./check-versions')() 2 | 3 | process.env.NODE_ENV = 'production' 4 | process.env.PLATFORM = process.argv[process.argv.length - 1] || 'wx' 5 | 6 | var ora = require('ora') 7 | var rm = require('rimraf') 8 | var path = require('path') 9 | var chalk = require('chalk') 10 | var webpack = require('webpack') 11 | var config = require('../config') 12 | var webpackConfig = require('./webpack.prod.conf') 13 | var utils = require('./utils') 14 | 15 | var spinner = ora('building for production...') 16 | spinner.start() 17 | 18 | rm(path.join(config.build.assetsRoot, '*'), err => { 19 | if (err) throw err 20 | webpack(webpackConfig, function (err, stats) { 21 | spinner.stop() 22 | if (err) throw err 23 | if (process.env.PLATFORM === 'swan') { 24 | utils.writeFrameworkinfo() 25 | } 26 | process.stdout.write(stats.toString({ 27 | colors: true, 28 | modules: false, 29 | children: false, 30 | chunks: false, 31 | chunkModules: false 32 | }) + '\n\n') 33 | 34 | if (stats.hasErrors()) { 35 | console.log(chalk.red(' Build failed with errors.\n')) 36 | process.exit(1) 37 | } 38 | 39 | console.log(chalk.cyan(' Build complete.\n')) 40 | console.log(chalk.yellow( 41 | ' Tip: built files are meant to be served over an HTTP server.\n' + 42 | ' Opening index.html over file:// won\'t work.\n' 43 | )) 44 | }) 45 | }) 46 | -------------------------------------------------------------------------------- /build/check-versions.js: -------------------------------------------------------------------------------- 1 | var chalk = require('chalk') 2 | var semver = require('semver') 3 | var packageConfig = require('../package.json') 4 | var shell = require('shelljs') 5 | function exec (cmd) { 6 | return require('child_process').execSync(cmd).toString().trim() 7 | } 8 | 9 | var versionRequirements = [ 10 | { 11 | name: 'node', 12 | currentVersion: semver.clean(process.version), 13 | versionRequirement: packageConfig.engines.node 14 | } 15 | ] 16 | 17 | if (shell.which('npm')) { 18 | versionRequirements.push({ 19 | name: 'npm', 20 | currentVersion: exec('npm --version'), 21 | versionRequirement: packageConfig.engines.npm 22 | }) 23 | } 24 | 25 | module.exports = function () { 26 | var warnings = [] 27 | for (var i = 0; i < versionRequirements.length; i++) { 28 | var mod = versionRequirements[i] 29 | if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) { 30 | warnings.push(mod.name + ': ' + 31 | chalk.red(mod.currentVersion) + ' should be ' + 32 | chalk.green(mod.versionRequirement) 33 | ) 34 | } 35 | } 36 | 37 | if (warnings.length) { 38 | console.log('') 39 | console.log(chalk.yellow('To use this template, you must update following to modules:')) 40 | console.log() 41 | for (var i = 0; i < warnings.length; i++) { 42 | var warning = warnings[i] 43 | console.log(' ' + warning) 44 | } 45 | console.log() 46 | process.exit(1) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /build/dev-client.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | require('eventsource-polyfill') 3 | var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true') 4 | 5 | hotClient.subscribe(function (event) { 6 | if (event.action === 'reload') { 7 | window.location.reload() 8 | } 9 | }) 10 | -------------------------------------------------------------------------------- /build/dev-server.js: -------------------------------------------------------------------------------- 1 | require('./check-versions')() 2 | 3 | process.env.PLATFORM = process.argv[process.argv.length - 1] || 'wx' 4 | var config = require('../config') 5 | if (!process.env.NODE_ENV) { 6 | process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV) 7 | } 8 | 9 | // var opn = require('opn') 10 | var path = require('path') 11 | var express = require('express') 12 | var webpack = require('webpack') 13 | var proxyMiddleware = require('http-proxy-middleware') 14 | var portfinder = require('portfinder') 15 | var webpackConfig = require('./webpack.dev.conf') 16 | var utils = require('./utils') 17 | 18 | // default port where dev server listens for incoming traffic 19 | var port = process.env.PORT || config.dev.port 20 | // automatically open browser, if not set will be false 21 | var autoOpenBrowser = !!config.dev.autoOpenBrowser 22 | // Define HTTP proxies to your custom API backend 23 | // https://github.com/chimurai/http-proxy-middleware 24 | var proxyTable = config.dev.proxyTable 25 | 26 | var app = express() 27 | var compiler = webpack(webpackConfig) 28 | if (process.env.PLATFORM === 'swan') { 29 | utils.writeFrameworkinfo() 30 | } 31 | 32 | // var devMiddleware = require('webpack-dev-middleware')(compiler, { 33 | // publicPath: webpackConfig.output.publicPath, 34 | // quiet: true 35 | // }) 36 | 37 | // var hotMiddleware = require('webpack-hot-middleware')(compiler, { 38 | // log: false, 39 | // heartbeat: 2000 40 | // }) 41 | // force page reload when html-webpack-plugin template changes 42 | // compiler.plugin('compilation', function (compilation) { 43 | // compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) { 44 | // hotMiddleware.publish({ action: 'reload' }) 45 | // cb() 46 | // }) 47 | // }) 48 | 49 | // proxy api requests 50 | Object.keys(proxyTable).forEach(function (context) { 51 | var options = proxyTable[context] 52 | if (typeof options === 'string') { 53 | options = { target: options } 54 | } 55 | app.use(proxyMiddleware(options.filter || context, options)) 56 | }) 57 | 58 | // handle fallback for HTML5 history API 59 | app.use(require('connect-history-api-fallback')()) 60 | 61 | // serve webpack bundle output 62 | // app.use(devMiddleware) 63 | 64 | // enable hot-reload and state-preserving 65 | // compilation error display 66 | // app.use(hotMiddleware) 67 | 68 | // serve pure static assets 69 | var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory) 70 | app.use(staticPath, express.static('./static')) 71 | 72 | // var uri = 'http://localhost:' + port 73 | 74 | var _resolve 75 | var readyPromise = new Promise(resolve => { 76 | _resolve = resolve 77 | }) 78 | 79 | // console.log('> Starting dev server...') 80 | // devMiddleware.waitUntilValid(() => { 81 | // console.log('> Listening at ' + uri + '\n') 82 | // // when env is testing, don't need open it 83 | // if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') { 84 | // opn(uri) 85 | // } 86 | // _resolve() 87 | // }) 88 | 89 | module.exports = new Promise((resolve, reject) => { 90 | portfinder.basePort = port 91 | portfinder.getPortPromise() 92 | .then(newPort => { 93 | if (port !== newPort) { 94 | console.log(`${port}端口被占用,开启新端口${newPort}`) 95 | } 96 | var server = app.listen(newPort, 'localhost') 97 | // for 小程序的文件保存机制 98 | require('webpack-dev-middleware-hard-disk')(compiler, { 99 | publicPath: webpackConfig.output.publicPath, 100 | quiet: true 101 | }) 102 | resolve({ 103 | ready: readyPromise, 104 | close: () => { 105 | server.close() 106 | } 107 | }) 108 | }).catch(error => { 109 | console.log('没有找到空闲端口,请打开任务管理器杀死进程端口再试', error) 110 | }) 111 | }) 112 | -------------------------------------------------------------------------------- /build/utils.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var fs = require('fs') 3 | var config = require('../config') 4 | var ExtractTextPlugin = require('extract-text-webpack-plugin') 5 | var mpvueInfo = require('../node_modules/mpvue/package.json') 6 | var packageInfo = require('../package.json') 7 | var mkdirp = require('mkdirp') 8 | 9 | exports.assetsPath = function (_path) { 10 | var assetsSubDirectory = process.env.NODE_ENV === 'production' 11 | ? config.build.assetsSubDirectory 12 | : config.dev.assetsSubDirectory 13 | return path.posix.join(assetsSubDirectory, _path) 14 | } 15 | 16 | exports.cssLoaders = function (options) { 17 | options = options || {} 18 | 19 | var cssLoader = { 20 | loader: 'css-loader', 21 | options: { 22 | minimize: process.env.NODE_ENV === 'production', 23 | sourceMap: options.sourceMap 24 | } 25 | } 26 | 27 | var postcssLoader = { 28 | loader: 'postcss-loader', 29 | options: { 30 | sourceMap: true 31 | } 32 | } 33 | 34 | var px2rpxLoader = { 35 | loader: 'px2rpx-loader', 36 | options: { 37 | baseDpr: 1, 38 | rpxUnit: 0.5 39 | } 40 | } 41 | 42 | // generate loader string to be used with extract text plugin 43 | function generateLoaders (loader, loaderOptions) { 44 | var loaders = [cssLoader, px2rpxLoader, postcssLoader] 45 | if (loader) { 46 | loaders.push({ 47 | loader: loader + '-loader', 48 | options: Object.assign({}, loaderOptions, { 49 | sourceMap: options.sourceMap 50 | }) 51 | }) 52 | } 53 | 54 | // Extract CSS when that option is specified 55 | // (which is the case during production build) 56 | if (options.extract) { 57 | return ExtractTextPlugin.extract({ 58 | use: loaders, 59 | fallback: 'vue-style-loader' 60 | }) 61 | } else { 62 | return ['vue-style-loader'].concat(loaders) 63 | } 64 | } 65 | 66 | // https://vue-loader.vuejs.org/en/configurations/extract-css.html 67 | return { 68 | css: generateLoaders(), 69 | wxss: generateLoaders(), 70 | postcss: generateLoaders(), 71 | less: generateLoaders('less'), 72 | sass: generateLoaders('sass', { indentedSyntax: true }), 73 | scss: generateLoaders('sass'), 74 | stylus: generateLoaders('stylus'), 75 | styl: generateLoaders('stylus') 76 | } 77 | } 78 | 79 | // Generate loaders for standalone style files (outside of .vue) 80 | exports.styleLoaders = function (options) { 81 | var output = [] 82 | var loaders = exports.cssLoaders(options) 83 | for (var extension in loaders) { 84 | var loader = loaders[extension] 85 | output.push({ 86 | test: new RegExp('\\.' + extension + '$'), 87 | use: loader 88 | }) 89 | } 90 | return output 91 | } 92 | 93 | const writeFile = async (filePath, content) => { 94 | let dir = path.dirname(filePath) 95 | let exist = fs.existsSync(dir) 96 | if (!exist) { 97 | await mkdirp(dir) 98 | } 99 | await fs.writeFileSync(filePath, content, 'utf8') 100 | } 101 | 102 | exports.writeFrameworkinfo = function () { 103 | var buildInfo = { 104 | 'toolName': mpvueInfo.name, 105 | 'toolFrameWorkVersion': mpvueInfo.version, 106 | 'toolCliVersion': packageInfo.mpvueTemplateProjectVersion || '', 107 | 'createTime': Date.now() 108 | } 109 | 110 | var content = JSON.stringify(buildInfo) 111 | var fileName = '.frameworkinfo' 112 | var rootDir = path.resolve(__dirname, `../${fileName}`) 113 | var distDir = path.resolve(config.build.assetsRoot, `./${fileName}`) 114 | 115 | writeFile(rootDir, content) 116 | writeFile(distDir, content) 117 | } 118 | -------------------------------------------------------------------------------- /build/vue-loader.conf.js: -------------------------------------------------------------------------------- 1 | var utils = require('./utils') 2 | var config = require('../config') 3 | // var isProduction = process.env.NODE_ENV === 'production' 4 | // for mp 5 | var isProduction = true 6 | 7 | module.exports = { 8 | loaders: Object.assign(utils.cssLoaders({ 9 | sourceMap: isProduction 10 | ? config.build.productionSourceMap 11 | : config.dev.cssSourceMap, 12 | extract: isProduction 13 | }), { 14 | ts: [ 15 | 'babel-loader', 16 | { 17 | loader: 'awesome-typescript-loader', 18 | options: { 19 | // errorsAsWarnings: true, 20 | useCache: true, 21 | } 22 | }, 23 | // // *.vue文件直接写ts,使用的时候,注释掉上面的awesome-typescript-loader 24 | // { 25 | // loader: 'ts-loader', 26 | // options: { 27 | // // errorsAsWarnings: true, 28 | // appendTsSuffixTo: [/\.vue$/], 29 | // } 30 | // }, 31 | ] 32 | }), 33 | transformToRequire: { 34 | video: 'src', 35 | source: 'src', 36 | img: 'src', 37 | image: 'xlink:href' 38 | }, 39 | fileExt: config.build.fileExt 40 | } 41 | -------------------------------------------------------------------------------- /build/webpack.base.conf.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var fs = require('fs') 3 | var utils = require('./utils') 4 | var config = require('../config') 5 | var webpack = require('webpack') 6 | var merge = require('webpack-merge') 7 | var vueLoaderConfig = require('./vue-loader.conf') 8 | var MpvuePlugin = require('webpack-mpvue-asset-plugin') 9 | var glob = require('glob') 10 | var CopyWebpackPlugin = require('copy-webpack-plugin') 11 | var relative = require('relative') 12 | 13 | function resolve(dir) { 14 | return path.join(__dirname, '..', dir) 15 | } 16 | 17 | function getEntry(rootSrc, gb = '/pages/**/main.ts') { 18 | var map = {}; 19 | glob.sync(rootSrc + gb) 20 | .forEach(file => { 21 | var key = relative(rootSrc, file).replace('.ts', ''); 22 | map[key] = file; 23 | }) 24 | return map; 25 | } 26 | 27 | const appEntry = { app: resolve('./src/main.ts') } 28 | const pagesEntry = getEntry(resolve('./src')) 29 | //分包A 30 | const subpackagePagesEntry = getEntry(resolve('./src'), '/packageA/pages/**/main.ts') 31 | const entry = Object.assign({}, appEntry, pagesEntry, subpackagePagesEntry) 32 | 33 | let baseWebpackConfig = { 34 | // 如果要自定义生成的 dist 目录里面的文件路径, 35 | // 可以将 entry 写成 {'toPath': 'fromPath'} 的形式, 36 | // toPath 为相对于 dist 的路径, 例:index/demo,则生成的文件地址为 dist/index/demo.js 37 | entry, 38 | target: require('mpvue-webpack-target'), 39 | output: { 40 | path: config.build.assetsRoot, 41 | jsonpFunction: 'webpackJsonpMpvue', 42 | filename: '[name].js', 43 | publicPath: process.env.NODE_ENV === 'production' 44 | ? config.build.assetsPublicPath 45 | : config.dev.assetsPublicPath 46 | }, 47 | resolve: { 48 | extensions: ['.js', '.vue', '.json', '.ts',], 49 | alias: { 50 | 'vue': 'mpvue', 51 | '@': resolve('src'), 52 | 'debug': resolve('src/utils/debug'), 53 | 'lodash': resolve('vendor/lodash_export'), 54 | }, 55 | symlinks: false, 56 | aliasFields: ['mpvue', 'weapp', 'browser'], 57 | mainFields: ['browser', 'module', 'main'] 58 | }, 59 | module: { 60 | rules: [ 61 | { 62 | test: /\.vue$/, 63 | loader: 'mpvue-loader', 64 | options: vueLoaderConfig 65 | }, 66 | { 67 | test: /\.tsx?$/, 68 | // include: [resolve('src'), resolve('test')], 69 | exclude: /node_modules/, 70 | use: [ 71 | { 72 | loader: 'babel-loader', 73 | }, 74 | { 75 | loader: 'mpvue-loader', 76 | options: Object.assign({ checkMPEntry: true }, vueLoaderConfig) 77 | }, 78 | { 79 | // loader: 'ts-loader', 80 | loader: 'awesome-typescript-loader', 81 | options: { 82 | // errorsAsWarnings: true, 83 | useCache: true, 84 | } 85 | } 86 | ] 87 | }, 88 | // { 89 | // test: /\.less$/, 90 | // exclude: /node_modules/, 91 | // use: ExtractTextPlugin.extract({ 92 | // fallback: "style-loader", 93 | // use: [ 94 | // { 95 | // loader: 'css-loader', 96 | // options: { 97 | // importLoaders: 1, 98 | // url: false, 99 | // }, 100 | // }, 101 | // 'less-loader', 102 | // ], 103 | // }), 104 | // }, 105 | { 106 | test: /\.js$/, 107 | include: [resolve('src'), resolve('test')], 108 | use: [ 109 | 'babel-loader', 110 | { 111 | loader: 'mpvue-loader', 112 | options: Object.assign({ checkMPEntry: true }, vueLoaderConfig) 113 | }, 114 | ] 115 | }, 116 | { 117 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, 118 | loader: 'url-loader', 119 | options: { 120 | limit: 10000, 121 | name: utils.assetsPath('img/[name].[ext]') 122 | } 123 | }, 124 | { 125 | test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, 126 | loader: 'url-loader', 127 | options: { 128 | limit: 10000, 129 | name: utils.assetsPath('media/[name].[ext]') 130 | } 131 | }, 132 | { 133 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, 134 | loader: 'url-loader', 135 | options: { 136 | limit: 10000, 137 | name: utils.assetsPath('fonts/[name].[ext]') 138 | } 139 | } 140 | ] 141 | }, 142 | plugins: [ 143 | // api 统一桥协议方案 144 | new webpack.DefinePlugin({ 145 | 'mpvue': 'global.mpvue', 146 | 'mpvuePlatform': 'global.mpvuePlatform' 147 | }), 148 | new MpvuePlugin(), 149 | new CopyWebpackPlugin([{ 150 | from: '**/*.json', 151 | to: '' 152 | }], { 153 | context: 'src/' 154 | }), 155 | new CopyWebpackPlugin([ 156 | { 157 | from: path.resolve(__dirname, '../static'), 158 | to: path.resolve(config.build.assetsRoot, './static'), 159 | ignore: ['.*'] 160 | } 161 | ]) 162 | ] 163 | } 164 | 165 | // 针对百度小程序,由于不支持通过 miniprogramRoot 进行自定义构建完的文件的根路径 166 | // 所以需要将项目根路径下面的 project.swan.json 拷贝到构建目录 167 | // 然后百度开发者工具将 dist/swan 作为项目根目录打 168 | const projectConfigMap = { 169 | tt: '../project.config.json', 170 | swan: '../project.swan.json' 171 | } 172 | 173 | const PLATFORM = process.env.PLATFORM 174 | if (/^(swan)|(tt)$/.test(PLATFORM)) { 175 | baseWebpackConfig = merge(baseWebpackConfig, { 176 | plugins: [ 177 | new CopyWebpackPlugin([{ 178 | from: path.resolve(__dirname, projectConfigMap[PLATFORM]), 179 | to: path.resolve(config.build.assetsRoot) 180 | }]) 181 | ] 182 | }) 183 | } 184 | 185 | module.exports = baseWebpackConfig 186 | -------------------------------------------------------------------------------- /build/webpack.dev.conf.js: -------------------------------------------------------------------------------- 1 | var utils = require('./utils') 2 | var webpack = require('webpack') 3 | var config = require('../config') 4 | var merge = require('webpack-merge') 5 | var baseWebpackConfig = require('./webpack.base.conf') 6 | // var HtmlWebpackPlugin = require('html-webpack-plugin') 7 | var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') 8 | var MpvueVendorPlugin = require('webpack-mpvue-vendor-plugin') 9 | 10 | // copy from ./webpack.prod.conf.js 11 | var path = require('path') 12 | var ExtractTextPlugin = require('extract-text-webpack-plugin') 13 | var CopyWebpackPlugin = require('copy-webpack-plugin') 14 | var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') 15 | 16 | // add hot-reload related code to entry chunks 17 | // Object.keys(baseWebpackConfig.entry).forEach(function (name) { 18 | // baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]) 19 | // }) 20 | 21 | module.exports = merge(baseWebpackConfig, { 22 | module: { 23 | rules: utils.styleLoaders({ 24 | sourceMap: config.dev.cssSourceMap, 25 | extract: true 26 | }) 27 | }, 28 | // cheap-module-eval-source-map is faster for development 29 | // devtool: '#cheap-module-eval-source-map', 30 | // devtool: '#source-map', 31 | output: { 32 | path: config.build.assetsRoot, 33 | // filename: utils.assetsPath('[name].[chunkhash].js'), 34 | // chunkFilename: utils.assetsPath('[id].[chunkhash].js') 35 | filename: utils.assetsPath('[name].js'), 36 | chunkFilename: utils.assetsPath('[id].js') 37 | }, 38 | plugins: [ 39 | new webpack.DefinePlugin({ 40 | 'process.env': config.dev.env 41 | }), 42 | 43 | // copy from ./webpack.prod.conf.js 44 | // extract css into its own file 45 | new ExtractTextPlugin({ 46 | // filename: utils.assetsPath('[name].[contenthash].css') 47 | filename: utils.assetsPath(`[name].${config.dev.fileExt.style}`) 48 | }), 49 | // Compress extracted CSS. We are using this plugin so that possible 50 | // duplicated CSS from different components can be deduped. 51 | new OptimizeCSSPlugin({ 52 | cssProcessorOptions: { 53 | safe: true 54 | } 55 | }), 56 | new webpack.optimize.CommonsChunkPlugin({ 57 | name: 'common/vendor', 58 | minChunks: function (module, count) { 59 | // any required modules inside node_modules are extracted to vendor 60 | return ( 61 | module.resource && 62 | /\.js$/.test(module.resource) && 63 | module.resource.indexOf('node_modules') >= 0 64 | ) || count > 1 65 | } 66 | }), 67 | new webpack.optimize.CommonsChunkPlugin({ 68 | name: 'common/manifest', 69 | chunks: ['common/vendor'] 70 | }), 71 | new MpvueVendorPlugin({ 72 | platform: process.env.PLATFORM 73 | }), 74 | // https://github.com/glenjamin/webpack-hot-middleware#installation--usage 75 | // new webpack.HotModuleReplacementPlugin(), 76 | new webpack.NoEmitOnErrorsPlugin(), 77 | // https://github.com/ampedandwired/html-webpack-plugin 78 | // new HtmlWebpackPlugin({ 79 | // filename: 'index.html', 80 | // template: 'index.html', 81 | // inject: true 82 | // }), 83 | new FriendlyErrorsPlugin() 84 | ] 85 | }) 86 | -------------------------------------------------------------------------------- /build/webpack.prod.conf.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var utils = require('./utils') 3 | var webpack = require('webpack') 4 | var config = require('../config') 5 | var merge = require('webpack-merge') 6 | var baseWebpackConfig = require('./webpack.base.conf') 7 | var UglifyJsPlugin = require('uglifyjs-webpack-plugin') 8 | var CopyWebpackPlugin = require('copy-webpack-plugin') 9 | // var HtmlWebpackPlugin = require('html-webpack-plugin') 10 | var ExtractTextPlugin = require('extract-text-webpack-plugin') 11 | var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') 12 | var MpvueVendorPlugin = require('webpack-mpvue-vendor-plugin') 13 | var env = config.build.env 14 | 15 | var webpackConfig = merge(baseWebpackConfig, { 16 | module: { 17 | rules: utils.styleLoaders({ 18 | sourceMap: config.build.productionSourceMap, 19 | extract: true 20 | }) 21 | }, 22 | devtool: config.build.productionSourceMap ? '#source-map' : false, 23 | output: { 24 | path: config.build.assetsRoot, 25 | // filename: utils.assetsPath('[name].[chunkhash].js'), 26 | // chunkFilename: utils.assetsPath('[id].[chunkhash].js') 27 | filename: utils.assetsPath('[name].js'), 28 | chunkFilename: utils.assetsPath('[id].js') 29 | }, 30 | plugins: [ 31 | // http://vuejs.github.io/vue-loader/en/workflow/production.html 32 | new webpack.DefinePlugin({ 33 | 'process.env': env 34 | }), 35 | // extract css into its own file 36 | new ExtractTextPlugin({ 37 | // filename: utils.assetsPath('[name].[contenthash].css') 38 | filename: utils.assetsPath(`[name].${config.build.fileExt.style}`) 39 | }), 40 | // Compress extracted CSS. We are using this plugin so that possible 41 | // duplicated CSS from different components can be deduped. 42 | new OptimizeCSSPlugin({ 43 | cssProcessorOptions: { 44 | safe: true 45 | } 46 | }), 47 | // generate dist index.html with correct asset hash for caching. 48 | // you can customize output by editing /index.html 49 | // see https://github.com/ampedandwired/html-webpack-plugin 50 | // new HtmlWebpackPlugin({ 51 | // filename: config.build.index, 52 | // template: 'index.html', 53 | // inject: true, 54 | // minify: { 55 | // removeComments: true, 56 | // collapseWhitespace: true, 57 | // removeAttributeQuotes: true 58 | // // more options: 59 | // // https://github.com/kangax/html-minifier#options-quick-reference 60 | // }, 61 | // // necessary to consistently work with multiple chunks via CommonsChunkPlugin 62 | // chunksSortMode: 'dependency' 63 | // }), 64 | // keep module.id stable when vender modules does not change 65 | new webpack.HashedModuleIdsPlugin(), 66 | // split vendor js into its own file 67 | new webpack.optimize.CommonsChunkPlugin({ 68 | name: 'common/vendor', 69 | minChunks: function (module, count) { 70 | // any required modules inside node_modules are extracted to vendor 71 | return ( 72 | module.resource && 73 | /\.js$/.test(module.resource) && 74 | module.resource.indexOf('node_modules') >= 0 75 | ) || count > 1 76 | } 77 | }), 78 | // extract webpack runtime and module manifest to its own file in order to 79 | // prevent vendor hash from being updated whenever app bundle is updated 80 | new webpack.optimize.CommonsChunkPlugin({ 81 | name: 'common/manifest', 82 | chunks: ['common/vendor'] 83 | }), 84 | new MpvueVendorPlugin({ 85 | platform: process.env.PLATFORM 86 | }) 87 | ] 88 | }) 89 | 90 | // if (config.build.productionGzip) { 91 | // var CompressionWebpackPlugin = require('compression-webpack-plugin') 92 | 93 | // webpackConfig.plugins.push( 94 | // new CompressionWebpackPlugin({ 95 | // asset: '[path].gz[query]', 96 | // algorithm: 'gzip', 97 | // test: new RegExp( 98 | // '\\.(' + 99 | // config.build.productionGzipExtensions.join('|') + 100 | // ')$' 101 | // ), 102 | // threshold: 10240, 103 | // minRatio: 0.8 104 | // }) 105 | // ) 106 | // } 107 | 108 | if (config.build.bundleAnalyzerReport) { 109 | var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin 110 | webpackConfig.plugins.push(new BundleAnalyzerPlugin()) 111 | } 112 | 113 | var useUglifyJs = process.env.PLATFORM !== 'swan' 114 | if (useUglifyJs) { 115 | webpackConfig.plugins.push(new UglifyJsPlugin({ 116 | sourceMap: true 117 | })) 118 | } 119 | 120 | module.exports = webpackConfig 121 | -------------------------------------------------------------------------------- /config/dev.env.js: -------------------------------------------------------------------------------- 1 | var merge = require('webpack-merge') 2 | var prodEnv = require('./prod.env') 3 | 4 | module.exports = merge(prodEnv, { 5 | NODE_ENV: '"development"' 6 | }) 7 | -------------------------------------------------------------------------------- /config/index.js: -------------------------------------------------------------------------------- 1 | // see http://vuejs-templates.github.io/webpack for documentation. 2 | var path = require('path') 3 | var fileExtConfig = { 4 | swan: { 5 | template: 'swan', 6 | script: 'js', 7 | style: 'css', 8 | platform: 'swan' 9 | }, 10 | tt: { 11 | template: 'ttml', 12 | script: 'js', 13 | style: 'ttss', 14 | platform: 'tt' 15 | }, 16 | wx: { 17 | template: 'wxml', 18 | script: 'js', 19 | style: 'wxss', 20 | platform: 'wx' 21 | }, 22 | my: { 23 | template: 'axml', 24 | script: 'js', 25 | style: 'acss', 26 | platform: 'my' 27 | } 28 | } 29 | var fileExt = fileExtConfig[process.env.PLATFORM] 30 | 31 | module.exports = { 32 | build: { 33 | env: require('./prod.env'), 34 | index: path.resolve(__dirname, `../dist/${fileExt.platform}/index.html`), 35 | assetsRoot: path.resolve(__dirname, `../dist/${fileExt.platform}`), 36 | assetsSubDirectory: '', 37 | assetsPublicPath: '/', 38 | productionSourceMap: false, 39 | // Gzip off by default as many popular static hosts such as 40 | // Surge or Netlify already gzip all static assets for you. 41 | // Before setting to `true`, make sure to: 42 | // npm install --save-dev compression-webpack-plugin 43 | productionGzip: false, 44 | productionGzipExtensions: ['js', 'css'], 45 | // Run the build command with an extra argument to 46 | // View the bundle analyzer report after build finishes: 47 | // `npm run build --report` 48 | // Set to `true` or `false` to always turn it on or off 49 | bundleAnalyzerReport: process.env.npm_config_report, 50 | fileExt: fileExt 51 | }, 52 | dev: { 53 | env: require('./dev.env'), 54 | port: 7100, 55 | // 在小程序开发者工具中不需要自动打开浏览器 56 | autoOpenBrowser: false, 57 | assetsSubDirectory: '', 58 | assetsPublicPath: '/', 59 | proxyTable: {}, 60 | // CSS Sourcemaps off by default because relative paths are "buggy" 61 | // with this option, according to the CSS-Loader README 62 | // (https://github.com/webpack/css-loader#sourcemaps) 63 | // In our experience, they generally work as expected, 64 | // just be aware of this issue when enabling this option. 65 | cssSourceMap: false, 66 | fileExt: fileExt 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /config/prod.env.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | NODE_ENV: '"production"' 3 | } 4 | -------------------------------------------------------------------------------- /dev.md: -------------------------------------------------------------------------------- 1 | ```bash 2 | yarn upgrade mpvue@latest mpvue-loader@latest mpvue-template-compiler@latest mpvue-webpack-target@latest 3 | 4 | rm -fr node_modules/mpvue-loader && ln -s ~/Projs/mpvue-loader node_modules/mpvue-loader 5 | rm -fr node_modules/mpvue-entry && ln -s ~/Projs/mpvue-entry node_modules/mpvue-entry 6 | ``` 7 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | wxmp-demo 6 | 7 | 8 |
9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mpvue-ts-demo", 3 | "version": "2.0.0", 4 | "description": "A Mpvue Typescript project", 5 | "author": "Wing Gao ", 6 | "private": true, 7 | "scripts": { 8 | "dev:wx": "node build/dev-server.js wx", 9 | "start:wx": "npm run dev:wx", 10 | "build:wx": "node build/build.js wx", 11 | "dev:swan": "node build/dev-server.js swan", 12 | "start:swan": "npm run dev:swan", 13 | "build:swan": "node build/build.js swan", 14 | "dev:tt": "node build/dev-server.js tt", 15 | "start:tt": "npm run dev:tt", 16 | "build:tt": "node build/build.js tt", 17 | "dev:my": "node build/dev-server.js my", 18 | "start:my": "npm run dev:my", 19 | "build:my": "node build/build.js my", 20 | "dev": "node build/dev-server.js wx", 21 | "start": "npm run dev", 22 | "build": "node build/build.js wx" 23 | }, 24 | "dependencies": { 25 | "debug": "^3.1.0", 26 | "flyio": "^0.6.9", 27 | "lodash": "^4.17.11", 28 | "vue": "^2.5.16", 29 | "vue-property-decorator": "^7.0.0", 30 | "mpvue": "^2.0.0", 31 | "vuex": "^3.0.1" 32 | }, 33 | "devDependencies": { 34 | "@types/node": "^9.4.7", 35 | "autoprefixer": "^7.1.2", 36 | "awesome-typescript-loader": "^4.0.1", 37 | "babel-eslint": "^7.1.1", 38 | "babel-plugin-transform-decorators-legacy": "^1.3.4", 39 | "cross-env": "^5.2.0", 40 | "eslint": "^3.19.0", 41 | "eslint-config-standard": "^6.2.1", 42 | "eslint-friendly-formatter": "^3.0.0", 43 | "eslint-loader": "^1.7.1", 44 | "eslint-plugin-html": "^3.0.0", 45 | "eslint-plugin-promise": "^3.4.0", 46 | "eslint-plugin-standard": "^2.0.1", 47 | "less": "^3.8.1", 48 | "less-loader": "^4.1.0", 49 | "mpvue-entry": "^1.4.7", 50 | "opn": "^5.1.0", 51 | "tencent-wx-app": "^1.1.201712221707", 52 | "typescript": "^2.7.2", 53 | "webpack-dev-middleware": "^1.10.0", 54 | "webpack-hot-middleware": "^2.18.0", 55 | "wechat-mp-types": "banxi1988/wechat-mp-types", 56 | "babel-core": "^6.22.1", 57 | "babel-loader": "^7.1.1", 58 | "babel-plugin-transform-runtime": "^6.22.0", 59 | "babel-preset-env": "^1.3.2", 60 | "babel-preset-stage-2": "^6.22.0", 61 | "babel-register": "^6.22.0", 62 | "chalk": "^2.4.0", 63 | "connect-history-api-fallback": "^1.3.0", 64 | "copy-webpack-plugin": "^4.5.1", 65 | "css-loader": "^0.28.11", 66 | "cssnano": "^3.10.0", 67 | "eventsource-polyfill": "^0.9.6", 68 | "express": "^4.16.3", 69 | "extract-text-webpack-plugin": "^3.0.2", 70 | "file-loader": "^1.1.11", 71 | "friendly-errors-webpack-plugin": "^1.7.0", 72 | "glob": "^7.1.2", 73 | "html-webpack-plugin": "^3.2.0", 74 | "http-proxy-middleware": "^0.18.0", 75 | "optimize-css-assets-webpack-plugin": "^3.2.0", 76 | "ora": "^2.0.0", 77 | "portfinder": "^1.0.13", 78 | "postcss-loader": "^2.1.4", 79 | "postcss-mpvue-wxss": "^1.0.0", 80 | "prettier": "~1.12.1", 81 | "px2rpx-loader": "^0.1.10", 82 | "relative": "^3.0.2", 83 | "rimraf": "^2.6.0", 84 | "semver": "^5.3.0", 85 | "shelljs": "^0.8.1", 86 | "uglifyjs-webpack-plugin": "^1.2.5", 87 | "url-loader": "^1.0.1", 88 | "vue-style-loader": "^4.1.0", 89 | "mkdirp": "^0.5.1", 90 | "mpvue-loader": "^2.0.0", 91 | "mpvue-template-compiler": "^2.0.0", 92 | "mpvue-webpack-target": "^1.0.3", 93 | "webpack-mpvue-vendor-plugin": "^2.0.0", 94 | "webpack-mpvue-asset-plugin": "^2.0.0", 95 | "webpack-bundle-analyzer": "^2.2.1", 96 | "webpack-dev-middleware-hard-disk": "^1.12.0", 97 | "webpack-merge": "^4.1.0", 98 | "webpack": "^3.11.0" 99 | }, 100 | "engines": { 101 | "node": ">= 4.0.0", 102 | "npm": ">= 3.0.0" 103 | }, 104 | "browserslist": [ 105 | "> 1%", 106 | "last 2 versions", 107 | "not ie <= 8" 108 | ] 109 | } 110 | -------------------------------------------------------------------------------- /project.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "description": "项目配置文件。", 3 | "setting": { 4 | "urlCheck": true, 5 | "es6": false, 6 | "postcss": true, 7 | "minified": true, 8 | "newFeature": true 9 | }, 10 | "miniprogramRoot": "dist/wx/", 11 | "compileType": "miniprogram", 12 | "appid": "wx0d2a71485f4888c4", 13 | "projectname": "mp_demo", 14 | "simulatorType": "wechat", 15 | "simulatorPluginLibVersion": {}, 16 | "condition": { 17 | "search": { 18 | "current": -1, 19 | "list": [] 20 | }, 21 | "conversation": { 22 | "current": -1, 23 | "list": [] 24 | }, 25 | "game": { 26 | "currentL": -1, 27 | "list": [] 28 | }, 29 | "miniprogram": { 30 | "current": -1, 31 | "list": [] 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /src/App.vue: -------------------------------------------------------------------------------- 1 | 2 | 3 | 22 | -------------------------------------------------------------------------------- /src/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "pages": [ 3 | "pages/index/main", 4 | "pages/logs/main", 5 | "pages/counter/main", 6 | "pages/page2/main", 7 | "pages/testExtend/main" 8 | ], 9 | "subPackages": [ 10 | { 11 | "root": "packageA", 12 | "pages": [ 13 | "pages/index/main" 14 | ] 15 | } 16 | ], 17 | "window": { 18 | "backgroundTextStyle": "light", 19 | "navigationBarBackgroundColor": "#fff", 20 | "navigationBarTitleText": "WeChat", 21 | "navigationBarTextStyle": "black" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/app.ts: -------------------------------------------------------------------------------- 1 | import { Vue, Component } from 'vue-property-decorator' 2 | import Api from '@/data/api' 3 | const debug = require('debug')('log:App') 4 | 5 | declare module "vue/types/vue" { 6 | interface Vue { 7 | $mp: any; 8 | } 9 | } 10 | 11 | // 必须使用装饰器的方式来指定components 12 | @Component({ 13 | mpType: 'app', // mpvue特定 14 | } as any) 15 | class App extends Vue { 16 | // app hook 17 | onLaunch() { 18 | let opt = this.$root.$mp.appOptions 19 | debug('onLaunch', opt) 20 | Api.login().then(res => { 21 | debug('login', res) 22 | }) 23 | } 24 | 25 | onShow() { 26 | debug('onShow') 27 | } 28 | 29 | onHide() { 30 | debug('onHide') 31 | } 32 | 33 | mounted() { // vue hook 34 | debug('mounted') 35 | } 36 | } 37 | 38 | export default App 39 | -------------------------------------------------------------------------------- /src/components/card.vue: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 15 | 16 | 21 | -------------------------------------------------------------------------------- /src/components/compb.ts: -------------------------------------------------------------------------------- 1 | import { Vue, Component, Prop } from 'vue-property-decorator' 2 | 3 | const debug = require('debug')('log:Comp/CompB') 4 | 5 | // 必须使用装饰器的方式来指定component 6 | @Component({ 7 | // props: { 8 | // text: String 9 | // } 10 | }) 11 | class CompB extends Vue { 12 | @Prop({ default: '1' }) //注意用法! 13 | text: string; 14 | 15 | ver: number = 2; 16 | 17 | onShow() { 18 | debug('onShow') 19 | } 20 | 21 | onHide() { 22 | debug('onHide') 23 | } 24 | 25 | mounted() { // vue hook 26 | debug('mounted') 27 | } 28 | } 29 | 30 | export default CompB 31 | -------------------------------------------------------------------------------- /src/components/compb.vue: -------------------------------------------------------------------------------- 1 | 8 | 9 | 11 | 12 | 17 | -------------------------------------------------------------------------------- /src/data/api.ts: -------------------------------------------------------------------------------- 1 | import Fly from "flyio/dist/npm/wx" 2 | import { map, merge } from 'lodash' 3 | let fly = new Fly 4 | 5 | let cookies = {} 6 | const HOST = 'https://127.0.0.1' // 更改 7 | //添加请求拦截器 8 | fly.interceptors.request.use((request) => { 9 | //给所有请求添加自定义header 10 | request.headers["Cookie"] = map(cookies, (v, k) => k + '=' + v).join(';') 11 | //打印出请求体 12 | console.log(request.body) 13 | //终止请求 14 | //var err=new Error("xxx") 15 | //err.request=request 16 | //return Promise.reject(new Error("")) 17 | 18 | //可以显式返回request, 也可以不返回,没有返回值时拦截器中默认返回request 19 | return request; 20 | }) 21 | 22 | //添加响应拦截器,响应拦截器会在then/catch处理之前执行 23 | fly.interceptors.response.use( 24 | (response) => { 25 | if (response.request.url.indexOf(HOST) == 0) { 26 | let hcks = response.headers['set-cookie'] || response.headers['Set-Cookie'] 27 | if (hcks != null) { 28 | hcks.forEach(v => { 29 | let ck = v.split(';')[0].split('=') 30 | cookies[ck[0]] = ck[1] 31 | }) 32 | } 33 | } 34 | //只将请求结果的data字段返回 35 | return response.data 36 | }, 37 | (err) => { 38 | //发生网络错误后会走到这里 39 | //return Promise.resolve("ssss") 40 | } 41 | ) 42 | 43 | function postForm(url, data) { 44 | return fly.request(url, data, { 45 | method: 'post', 46 | headers: { 'content-type': 'application/x-www-form-urlencoded' }, 47 | }) 48 | } 49 | interface WxApiOpt { 50 | success: (res: T) => void 51 | fail: (e: any) => void 52 | } 53 | 54 | function wxApiToPromise(api: (a: WxApiOpt) => void, arg1?): Promise { 55 | return new Promise((resolve, reject) => { 56 | let opt = merge({ 57 | success(r) { 58 | resolve(r) 59 | }, 60 | fail(e) { 61 | reject(e) 62 | } 63 | }, arg1) 64 | api(opt) 65 | }) 66 | } 67 | 68 | const Api = { 69 | login() { 70 | return wxApiToPromise(wx.login, {}).then(res => { 71 | console.log(res.code) 72 | return res 73 | }) 74 | }, 75 | testForm() { 76 | return postForm(HOST, { a: 1 }) 77 | } 78 | } 79 | export default Api 80 | 81 | -------------------------------------------------------------------------------- /src/index.d.ts: -------------------------------------------------------------------------------- 1 | declare var require: any; 2 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { Component, Emit, Inject, Model, Prop, Provide, Vue, Watch } from 'vue-property-decorator'; 2 | import { VueConstructor } from "vue"; 3 | 4 | let isApp = false; //尝试mpvue-entry 5 | let MyApp; 6 | /* app-only-begin */ 7 | isApp = true; 8 | interface IMpVue extends VueConstructor { 9 | mpType: string 10 | } 11 | 12 | // 添加小程序hooks http://mpvue.com/mpvue/#_4 13 | Component.registerHooks([ 14 | // app 15 | 'onLaunch', // 初始化 16 | 'onShow', // 当小程序启动,或从后台进入前台显示 17 | 'onHide', // 当小程序从前台进入后台 18 | // pages 19 | 'onLoad', // 监听页面加载 20 | 'onShow', // 监听页面显示 21 | 'onReady', // 监听页面初次渲染完成 22 | 'onHide', // 监听页面隐藏 23 | 'onUnload', // 监听页面卸载 24 | 'onPullDownRefresh', // 监听用户下拉动作 25 | 'onReachBottom', // 页面上拉触底事件的处理函数 26 | 'onShareAppMessage', // 用户点击右上角分享 27 | 'onPageScroll', // 页面滚动 28 | 'onTabItemTap', //当前是 tab 页时, 点击 tab 时触发 (mpvue 0.0.16 支持) 29 | ]) 30 | 31 | Vue.config.productionTip = false 32 | // add this to handle exception 33 | Vue.config.errorHandler = function (err) { 34 | if (console && console.error) { 35 | console.error(err) 36 | } 37 | } 38 | /* app-only-end */ 39 | 40 | if (isApp) { 41 | // 在这个地方引入是为了registerHooks先执行 42 | MyApp = require('./App.vue').default as IMpVue 43 | }else { 44 | // MyApp = require('./index.vue') 45 | } 46 | 47 | 48 | const app = new Vue(MyApp) 49 | app.$mount() 50 | -------------------------------------------------------------------------------- /src/packageA/pages/index/index.ts: -------------------------------------------------------------------------------- 1 | import { Vue, Component } from 'vue-property-decorator' 2 | import { AppUrls } from '@/utils/consts.ts' 3 | import Card from '@/components/card.vue' // mpvue目前只支持的单文件组件 4 | 5 | const debug = require('debug')('log:PackageA/Index') 6 | // 必须使用装饰器的方式来指定component 7 | @Component({ 8 | components: { 9 | Card, 10 | } 11 | }) 12 | class Index extends Vue { 13 | AppUrls = AppUrls 14 | ver: number = 123 15 | 16 | onShow() { // 小程序 hook 17 | debug('onShow') 18 | } 19 | 20 | mounted() { // vue hook 21 | debug('mounted') 22 | } 23 | } 24 | 25 | export default Index 26 | -------------------------------------------------------------------------------- /src/packageA/pages/index/index.vue: -------------------------------------------------------------------------------- 1 | 9 | 10 | 12 | 13 | 14 | 29 | -------------------------------------------------------------------------------- /src/packageA/pages/index/main.ts: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import App from './index.vue' 3 | 4 | const app = new Vue(App) 5 | app.$mount() 6 | -------------------------------------------------------------------------------- /src/packageA/pages/index/page.json: -------------------------------------------------------------------------------- 1 | { 2 | "navigationBarTitleText": "mpvue-ts-demo" 3 | } 4 | -------------------------------------------------------------------------------- /src/pages.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | path: 'pages/index/index', 4 | config: { 5 | navigationBarTitleText: '主页' 6 | } 7 | }, 8 | { 9 | path: 'pages/index/main', 10 | subPackage: true 11 | } 12 | // { 13 | // path: 'pages/news/detail', 14 | // config: { 15 | // navigationBarTitleText: '文章详情' 16 | // } 17 | // }, 18 | // { 19 | // path: 'pages/news/comment', 20 | // config: { 21 | // navigationBarTitleText: '评论列表' 22 | // } 23 | // }, 24 | // { 25 | // path: 'pages/quanzi/list', 26 | // config: { 27 | // navigationBarTitleText: '圈子', 28 | // enablePullDownRefresh: true 29 | // } 30 | // }, 31 | // { 32 | // path: 'pages/quanzi/detail', 33 | // config: { 34 | // navigationBarTitleText: '圈子详情' 35 | // } 36 | // } 37 | ] 38 | -------------------------------------------------------------------------------- /src/pages/counter/counter.ts: -------------------------------------------------------------------------------- 1 | import { Component, Emit, Vue } from 'vue-property-decorator' 2 | import { AppUrls } from '@/utils/consts.ts' 3 | // Use Vuex 4 | import store from './store' 5 | const debug = require('debug')('log:Page/Counter') 6 | 7 | @Component 8 | export default class Counter extends Vue { 9 | AppUrls = AppUrls 10 | 11 | // computed 12 | get count () { 13 | return store.state.count 14 | } 15 | 16 | increment() { 17 | debug('hello4') 18 | store.commit('increment') 19 | } 20 | 21 | decrement() { 22 | store.commit('decrement') 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/pages/counter/index.vue: -------------------------------------------------------------------------------- 1 | 12 | 13 | 15 | 16 | 31 | -------------------------------------------------------------------------------- /src/pages/counter/main.ts: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import App from './index.vue' 3 | 4 | const app = new Vue(App) 5 | app.$mount() 6 | -------------------------------------------------------------------------------- /src/pages/counter/store.ts: -------------------------------------------------------------------------------- 1 | // https://vuex.vuejs.org/zh-cn/intro.html 2 | // make sure to call Vue.use(Vuex) if using a module system 3 | import Vue from 'vue' 4 | import Vuex from 'vuex' 5 | 6 | Vue.use(Vuex as any) 7 | 8 | const store = new Vuex.Store({ 9 | state: { 10 | count: 0 11 | }, 12 | mutations: { 13 | increment: (state) => { 14 | const obj = state 15 | obj.count += 1 16 | }, 17 | decrement: (state) => { 18 | const obj = state 19 | obj.count -= 1 20 | } 21 | } 22 | }) 23 | 24 | export default store 25 | -------------------------------------------------------------------------------- /src/pages/index/index.less: -------------------------------------------------------------------------------- 1 | // 外部less 2 | .counter-warp { 3 | .home { 4 | color: mediumvioletred; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src/pages/index/index.ts: -------------------------------------------------------------------------------- 1 | import { Vue, Component } from 'vue-property-decorator' 2 | import { AppUrls } from '@/utils/consts.ts' 3 | import Card from '@/components/card.vue' // mpvue目前只支持的单文件组件 4 | import CompB from '@/components/compb.vue' // mpvue目前只支持的单文件组件 5 | 6 | const debug = require('debug')('log:Index') 7 | 8 | // 必须使用装饰器的方式来指定component 9 | @Component({ 10 | components: { 11 | Card, 12 | CompB, //注意,vue的组件在template中的用法,`CompB` 会被转成 `comp-b` 13 | } 14 | }) 15 | class Index extends Vue { 16 | AppUrls = AppUrls 17 | ver: number = 123 18 | 19 | onShow() { // 小程序 hook 20 | debug('onShow') 21 | } 22 | 23 | mounted() { // vue hook 24 | debug('mounted') 25 | } 26 | } 27 | 28 | export default Index 29 | -------------------------------------------------------------------------------- /src/pages/index/index.vue: -------------------------------------------------------------------------------- 1 | 13 | 14 | 16 | 17 | 18 | 35 | -------------------------------------------------------------------------------- /src/pages/index/main.ts: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import App from './index.vue' 3 | 4 | const app = new Vue(App) 5 | app.$mount() 6 | -------------------------------------------------------------------------------- /src/pages/logs/index.vue: -------------------------------------------------------------------------------- 1 | 10 | 11 | 32 | 33 | 44 | -------------------------------------------------------------------------------- /src/pages/logs/main.json: -------------------------------------------------------------------------------- 1 | { 2 | "navigationBarTitleText": "查看启动日志" 3 | } 4 | -------------------------------------------------------------------------------- /src/pages/logs/main.ts: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import App from './index.vue' 3 | 4 | const app = new Vue(App) 5 | app.$mount() 6 | -------------------------------------------------------------------------------- /src/pages/page2/index.vue: -------------------------------------------------------------------------------- 1 | 7 | 8 | 17 | 18 | 21 | -------------------------------------------------------------------------------- /src/pages/page2/main.ts: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import App from './index.vue' 3 | 4 | const app = new Vue(App) 5 | app.$mount() 6 | -------------------------------------------------------------------------------- /src/pages/testExtend/base.ts: -------------------------------------------------------------------------------- 1 | import { Vue, Component } from 'vue-property-decorator' 2 | 3 | @Component 4 | export default class BaseComp extends Vue { 5 | public ver: number = 123 6 | 7 | public testFun(): any { 8 | console.log('testFun from BaseComp') 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/pages/testExtend/index.ts: -------------------------------------------------------------------------------- 1 | import { Vue, Component, Mixins } from 'vue-property-decorator' 2 | import { AppUrls } from '@/utils/consts.ts' 3 | import BaseComp from './base' 4 | 5 | const debug = require('debug')('log:Index') 6 | 7 | // 必须使用装饰器的方式来指定component 8 | @Component 9 | class Index extends Mixins(BaseComp) { 10 | testFun2(){ 11 | console.log('testFun2') 12 | } 13 | onShow() { // 小程序 hook 14 | debug('onShow') 15 | } 16 | 17 | mounted() { // vue hook 18 | debug('mounted') 19 | } 20 | } 21 | 22 | export default Index 23 | -------------------------------------------------------------------------------- /src/pages/testExtend/index.vue: -------------------------------------------------------------------------------- 1 | 9 | 10 | 12 | 13 | 14 | 16 | -------------------------------------------------------------------------------- /src/pages/testExtend/main.ts: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import App from './index.vue' 3 | 4 | const app = new Vue(App) 5 | app.$mount() 6 | -------------------------------------------------------------------------------- /src/utils/consts.ts: -------------------------------------------------------------------------------- 1 | const pre = '/pages' 2 | export const AppUrls = { 3 | INDEX: pre + '/index/main', 4 | COUNTER: pre + '/counter/main', 5 | PACKAGE_A: '/packageA/pages/index/main', 6 | } 7 | -------------------------------------------------------------------------------- /src/utils/debug.js: -------------------------------------------------------------------------------- 1 | module.exports = (name) => { 2 | return function () { 3 | console.log.apply(null, [name].concat([].slice.call(arguments))) 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /src/utils/index.js: -------------------------------------------------------------------------------- 1 | function formatNumber (n) { 2 | const str = n.toString() 3 | return str[1] ? str : `0${str}` 4 | } 5 | 6 | export function formatTime (date) { 7 | const year = date.getFullYear() 8 | const month = date.getMonth() + 1 9 | const day = date.getDate() 10 | 11 | const hour = date.getHours() 12 | const minute = date.getMinutes() 13 | const second = date.getSeconds() 14 | 15 | const t1 = [year, month, day].map(formatNumber).join('/') 16 | const t2 = [hour, minute, second].map(formatNumber).join(':') 17 | 18 | return `${t1} ${t2}` 19 | } 20 | 21 | -------------------------------------------------------------------------------- /src/vue-shim.d.ts: -------------------------------------------------------------------------------- 1 | declare module "*.vue" { 2 | import Vue from "vue"; 3 | export default Vue; 4 | } 5 | -------------------------------------------------------------------------------- /static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WingGao/mpvue-ts-demo/ae9c5de8b498976de7ad353bb259d9e94167c390/static/.gitkeep -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | // 与 Vue 的浏览器支持保持一致 4 | "target": "es2015", 5 | // 这可以对 `this` 上的数据属性进行更严格的推断 6 | "strict": true, 7 | // 如果使用 webpack 2+ 或 rollup,可以利用 tree-shake: 8 | "module": "es2015", 9 | "moduleResolution": "node", 10 | "baseUrl": "./", 11 | "outDir": "./dist/", 12 | "paths": { 13 | "vue": [ 14 | "node_modules/mpvue" 15 | ], 16 | "@/*": [ 17 | "src/*" 18 | ] 19 | }, 20 | "types": [ 21 | "wechat-mp-types" 22 | ], 23 | "allowJs": true, 24 | "allowSyntheticDefaultImports": true, 25 | "noImplicitAny": false, 26 | "skipLibCheck": true, 27 | "strictPropertyInitialization": false, 28 | "experimentalDecorators": true 29 | }, 30 | "include": [ 31 | "./src/**/*" 32 | ], 33 | "exclude": [ 34 | "node_modules" 35 | ], 36 | "typeAcquisition": { 37 | "enable": true 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /vendor/lodash_export.js: -------------------------------------------------------------------------------- 1 | module.exports = require('./lodash') 2 | --------------------------------------------------------------------------------