├── .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 |5 | {{text}} 6 |
7 |4 | From CompB {{text}} {{ver}} 5 |
6 |测试继承
4 |ver: {{ ver }}
5 | 6 | 7 |