Browse Source

feat: init

allen 3 years ago
parent
commit
442ab9be20

+ 2
- 1
.gitignore View File

@@ -58,4 +58,5 @@ typings/
58 58
 # dotenv environment variables file
59 59
 .env
60 60
 
61
-
61
+*.DS_Store
62
+dist

+ 10
- 0
babel.config.js View File

@@ -0,0 +1,10 @@
1
+// babel-preset-taro 更多选项和默认值:
2
+// https://github.com/NervJS/taro/blob/next/packages/babel-preset-taro/README.md
3
+module.exports = {
4
+  presets: [
5
+    ['taro', {
6
+      framework: 'react',
7
+      ts: false
8
+    }]
9
+  ]
10
+}

+ 9
- 0
config/dev.js View File

@@ -0,0 +1,9 @@
1
+module.exports = {
2
+  env: {
3
+    NODE_ENV: '"development"'
4
+  },
5
+  defineConstants: {
6
+  },
7
+  mini: {},
8
+  h5: {}
9
+}

+ 70
- 0
config/index.js View File

@@ -0,0 +1,70 @@
1
+const config = {
2
+  projectName: 'myDemo',
3
+  date: '2020-7-22',
4
+  designWidth: 750,
5
+  deviceRatio: {
6
+    640: 2.34 / 2,
7
+    750: 1,
8
+    828: 1.81 / 2
9
+  },
10
+  sourceRoot: 'src',
11
+  outputRoot: 'dist',
12
+  plugins: [],
13
+  defineConstants: {
14
+  },
15
+  copy: {
16
+    patterns: [
17
+    ],
18
+    options: {
19
+    }
20
+  },
21
+  framework: 'react',
22
+  mini: {
23
+    postcss: {
24
+      pxtransform: {
25
+        enable: true,
26
+        config: {
27
+
28
+        }
29
+      },
30
+      url: {
31
+        enable: true,
32
+        config: {
33
+          limit: 1024 // 设定转换尺寸上限
34
+        }
35
+      },
36
+      cssModules: {
37
+        enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
38
+        config: {
39
+          namingPattern: 'module', // 转换模式,取值为 global/module
40
+          generateScopedName: '[name]__[local]___[hash:base64:5]'
41
+        }
42
+      }
43
+    }
44
+  },
45
+  h5: {
46
+    publicPath: '/',
47
+    staticDirectory: 'static',
48
+    postcss: {
49
+      autoprefixer: {
50
+        enable: true,
51
+        config: {
52
+        }
53
+      },
54
+      cssModules: {
55
+        enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
56
+        config: {
57
+          namingPattern: 'module', // 转换模式,取值为 global/module
58
+          generateScopedName: '[name]__[local]___[hash:base64:5]'
59
+        }
60
+      }
61
+    }
62
+  }
63
+}
64
+
65
+module.exports = function (merge) {
66
+  if (process.env.NODE_ENV === 'development') {
67
+    return merge({}, config, require('./dev'))
68
+  }
69
+  return merge({}, config, require('./prod'))
70
+}

+ 18
- 0
config/prod.js View File

@@ -0,0 +1,18 @@
1
+module.exports = {
2
+  env: {
3
+    NODE_ENV: '"production"'
4
+  },
5
+  defineConstants: {
6
+  },
7
+  mini: {},
8
+  h5: {
9
+    /**
10
+     * 如果h5端编译后体积过大,可以使用webpack-bundle-analyzer插件对打包体积进行分析。
11
+     * 参考代码如下:
12
+     * webpackChain (chain) {
13
+     *   chain.plugin('analyzer')
14
+     *     .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin, [])
15
+     * }
16
+     */
17
+  }
18
+}

+ 15918
- 0
package-lock.json
File diff suppressed because it is too large
View File


+ 59
- 0
package.json View File

@@ -0,0 +1,59 @@
1
+{
2
+  "name": "myDemo",
3
+  "version": "1.0.0",
4
+  "private": true,
5
+  "description": "test",
6
+  "templateInfo": {
7
+    "name": "default",
8
+    "typescript": false,
9
+    "css": "sass"
10
+  },
11
+  "scripts": {
12
+    "build:weapp": "taro build --type weapp",
13
+    "build:swan": "taro build --type swan",
14
+    "build:alipay": "taro build --type alipay",
15
+    "build:tt": "taro build --type tt",
16
+    "build:h5": "taro build --type h5",
17
+    "build:rn": "taro build --type rn",
18
+    "build:qq": "taro build --type qq",
19
+    "build:jd": "taro build --type jd",
20
+    "build:quickapp": "taro build --type quickapp",
21
+    "dev:weapp": "npm run build:weapp -- --watch",
22
+    "dev:swan": "npm run build:swan -- --watch",
23
+    "dev:alipay": "npm run build:alipay -- --watch",
24
+    "dev:tt": "npm run build:tt -- --watch",
25
+    "dev:h5": "npm run build:h5 -- --watch",
26
+    "dev:rn": "npm run build:rn -- --watch",
27
+    "dev:qq": "npm run build:qq -- --watch",
28
+    "dev:jd": "npm run build:jd -- --watch",
29
+    "dev:quickapp": "npm run build:quickapp -- --watch"
30
+  },
31
+  "browserslist": [
32
+    "last 3 versions",
33
+    "Android >= 4.1",
34
+    "ios >= 8"
35
+  ],
36
+  "dependencies": {
37
+    "@babel/runtime": "^7.7.7",
38
+    "@tarojs/components": "3.0.5",
39
+    "@tarojs/runtime": "3.0.5",
40
+    "@tarojs/taro": "3.0.5",
41
+    "@tarojs/react": "3.0.5",
42
+    "react-dom": "^16.10.0",
43
+    "react": "^16.10.0"
44
+  },
45
+  "devDependencies": {
46
+    "@types/webpack-env": "^1.13.6",
47
+    "@types/react": "^16.0.0",
48
+    "@tarojs/mini-runner": "3.0.5",
49
+    "@babel/core": "^7.8.0",
50
+    "@tarojs/webpack-runner": "3.0.5",
51
+    "babel-preset-taro": "3.0.5",
52
+    "eslint-config-taro": "3.0.5",
53
+    "eslint": "^6.8.0",
54
+    "eslint-plugin-react": "^7.8.2",
55
+    "eslint-plugin-import": "^2.12.0",
56
+    "eslint-plugin-react-hooks": "^1.6.1",
57
+    "stylelint": "9.3.0"
58
+  }
59
+}

+ 13
- 0
project.config.json View File

@@ -0,0 +1,13 @@
1
+{
2
+  "miniprogramRoot": "./dist",
3
+  "projectname": "myDemo",
4
+  "description": "test",
5
+  "appid": "touristappid",
6
+  "setting": {
7
+    "urlCheck": true,
8
+    "es6": false,
9
+    "postcss": false,
10
+    "minified": false
11
+  },
12
+  "compileType": "miniprogram"
13
+}

+ 11
- 0
src/app.config.js View File

@@ -0,0 +1,11 @@
1
+export default {
2
+  pages: [
3
+    'pages/index/index'
4
+  ],
5
+  window: {
6
+    backgroundTextStyle: 'light',
7
+    navigationBarBackgroundColor: '#fff',
8
+    navigationBarTitleText: 'WeChat',
9
+    navigationBarTextStyle: 'black'
10
+  }
11
+}

+ 20
- 0
src/app.js View File

@@ -0,0 +1,20 @@
1
+import { Component } from 'react'
2
+import './app.scss'
3
+
4
+class App extends Component {
5
+
6
+  componentDidMount () {}
7
+
8
+  componentDidShow () {}
9
+
10
+  componentDidHide () {}
11
+
12
+  componentDidCatchError () {}
13
+
14
+  // this.props.children 是将要会渲染的页面
15
+  render () {
16
+    return this.props.children
17
+  }
18
+}
19
+
20
+export default App

+ 0
- 0
src/app.scss View File


+ 961
- 0
src/components/miniapp-router/lib/router.js View File

@@ -0,0 +1,961 @@
1
+/*eslint-disable*/
2
+module.exports =
3
+/******/ (function(modules) { // webpackBootstrap
4
+/******/ 	// The module cache
5
+/******/ 	var installedModules = {};
6
+/******/
7
+/******/ 	// The require function
8
+/******/ 	function __webpack_require__(moduleId) {
9
+/******/
10
+/******/ 		// Check if module is in cache
11
+/******/ 		if(installedModules[moduleId]) {
12
+/******/ 			return installedModules[moduleId].exports;
13
+/******/ 		}
14
+/******/ 		// Create a new module (and put it into the cache)
15
+/******/ 		var module = installedModules[moduleId] = {
16
+/******/ 			i: moduleId,
17
+/******/ 			l: false,
18
+/******/ 			exports: {}
19
+/******/ 		};
20
+/******/
21
+/******/ 		// Execute the module function
22
+/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
23
+/******/
24
+/******/ 		// Flag the module as loaded
25
+/******/ 		module.l = true;
26
+/******/
27
+/******/ 		// Return the exports of the module
28
+/******/ 		return module.exports;
29
+/******/ 	}
30
+/******/
31
+/******/
32
+/******/ 	// expose the modules object (__webpack_modules__)
33
+/******/ 	__webpack_require__.m = modules;
34
+/******/
35
+/******/ 	// expose the module cache
36
+/******/ 	__webpack_require__.c = installedModules;
37
+/******/
38
+/******/ 	// define getter function for harmony exports
39
+/******/ 	__webpack_require__.d = function(exports, name, getter) {
40
+/******/ 		if(!__webpack_require__.o(exports, name)) {
41
+/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
42
+/******/ 		}
43
+/******/ 	};
44
+/******/
45
+/******/ 	// define __esModule on exports
46
+/******/ 	__webpack_require__.r = function(exports) {
47
+/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
48
+/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
49
+/******/ 		}
50
+/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
51
+/******/ 	};
52
+/******/
53
+/******/ 	// create a fake namespace object
54
+/******/ 	// mode & 1: value is a module id, require it
55
+/******/ 	// mode & 2: merge all properties of value into the ns
56
+/******/ 	// mode & 4: return value when already ns object
57
+/******/ 	// mode & 8|1: behave like require
58
+/******/ 	__webpack_require__.t = function(value, mode) {
59
+/******/ 		if(mode & 1) value = __webpack_require__(value);
60
+/******/ 		if(mode & 8) return value;
61
+/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
62
+/******/ 		var ns = Object.create(null);
63
+/******/ 		__webpack_require__.r(ns);
64
+/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
65
+/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
66
+/******/ 		return ns;
67
+/******/ 	};
68
+/******/
69
+/******/ 	// getDefaultExport function for compatibility with non-harmony modules
70
+/******/ 	__webpack_require__.n = function(module) {
71
+/******/ 		var getter = module && module.__esModule ?
72
+/******/ 			function getDefault() { return module['default']; } :
73
+/******/ 			function getModuleExports() { return module; };
74
+/******/ 		__webpack_require__.d(getter, 'a', getter);
75
+/******/ 		return getter;
76
+/******/ 	};
77
+/******/
78
+/******/ 	// Object.prototype.hasOwnProperty.call
79
+/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
80
+/******/
81
+/******/ 	// __webpack_public_path__
82
+/******/ 	__webpack_require__.p = "";
83
+/******/
84
+/******/
85
+/******/ 	// Load entry module and return exports
86
+/******/ 	return __webpack_require__(__webpack_require__.s = "./src/index.ts");
87
+/******/ })
88
+/************************************************************************/
89
+/******/ ({
90
+
91
+/***/ "./node_modules/path-to-regexp/index.js":
92
+/*!**********************************************!*\
93
+  !*** ./node_modules/path-to-regexp/index.jsx ***!
94
+  \**********************************************/
95
+/*! no static exports found */
96
+/***/ (function(module, exports) {
97
+
98
+/**
99
+ * Expose `pathToRegexp`.
100
+ */
101
+module.exports = pathToRegexp
102
+module.exports.parse = parse
103
+module.exports.compile = compile
104
+module.exports.tokensToFunction = tokensToFunction
105
+module.exports.tokensToRegExp = tokensToRegExp
106
+
107
+/**
108
+ * Default configs.
109
+ */
110
+var DEFAULT_DELIMITER = '/'
111
+
112
+/**
113
+ * The main path matching regexp utility.
114
+ *
115
+ * @type {RegExp}
116
+ */
117
+var PATH_REGEXP = new RegExp([
118
+  // Match escaped characters that would otherwise appear in future matches.
119
+  // This allows the user to escape special characters that won't transform.
120
+  '(\\\\.)',
121
+  // Match Express-style parameters and un-named parameters with a prefix
122
+  // and optional suffixes. Matches appear as:
123
+  //
124
+  // ":test(\\d+)?" => ["test", "\d+", undefined, "?"]
125
+  // "(\\d+)"  => [undefined, undefined, "\d+", undefined]
126
+  '(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?'
127
+].join('|'), 'g')
128
+
129
+/**
130
+ * Parse a string for the raw tokens.
131
+ *
132
+ * @param  {string}  str
133
+ * @param  {Object=} options
134
+ * @return {!Array}
135
+ */
136
+function parse (str, options) {
137
+  var tokens = []
138
+  var key = 0
139
+  var index = 0
140
+  var path = ''
141
+  var defaultDelimiter = (options && options.delimiter) || DEFAULT_DELIMITER
142
+  var whitelist = (options && options.whitelist) || undefined
143
+  var pathEscaped = false
144
+  var res
145
+
146
+  while ((res = PATH_REGEXP.exec(str)) !== null) {
147
+    var m = res[0]
148
+    var escaped = res[1]
149
+    var offset = res.index
150
+    path += str.slice(index, offset)
151
+    index = offset + m.length
152
+
153
+    // Ignore already escaped sequences.
154
+    if (escaped) {
155
+      path += escaped[1]
156
+      pathEscaped = true
157
+      continue
158
+    }
159
+
160
+    var prev = ''
161
+    var name = res[2]
162
+    var capture = res[3]
163
+    var group = res[4]
164
+    var modifier = res[5]
165
+
166
+    if (!pathEscaped && path.length) {
167
+      var k = path.length - 1
168
+      var c = path[k]
169
+      var matches = whitelist ? whitelist.indexOf(c) > -1 : true
170
+
171
+      if (matches) {
172
+        prev = c
173
+        path = path.slice(0, k)
174
+      }
175
+    }
176
+
177
+    // Push the current path onto the tokens.
178
+    if (path) {
179
+      tokens.push(path)
180
+      path = ''
181
+      pathEscaped = false
182
+    }
183
+
184
+    var repeat = modifier === '+' || modifier === '*'
185
+    var optional = modifier === '?' || modifier === '*'
186
+    var pattern = capture || group
187
+    var delimiter = prev || defaultDelimiter
188
+
189
+    tokens.push({
190
+      name: name || key++,
191
+      prefix: prev,
192
+      delimiter: delimiter,
193
+      optional: optional,
194
+      repeat: repeat,
195
+      pattern: pattern
196
+        ? escapeGroup(pattern)
197
+        : '[^' + escapeString(delimiter === defaultDelimiter ? delimiter : (delimiter + defaultDelimiter)) + ']+?'
198
+    })
199
+  }
200
+
201
+  // Push any remaining characters.
202
+  if (path || index < str.length) {
203
+    tokens.push(path + str.substr(index))
204
+  }
205
+
206
+  return tokens
207
+}
208
+
209
+/**
210
+ * Compile a string to a template function for the path.
211
+ *
212
+ * @param  {string}             str
213
+ * @param  {Object=}            options
214
+ * @return {!function(Object=, Object=)}
215
+ */
216
+function compile (str, options) {
217
+  return tokensToFunction(parse(str, options))
218
+}
219
+
220
+/**
221
+ * Expose a method for transforming tokens into the path function.
222
+ */
223
+function tokensToFunction (tokens) {
224
+  // Compile all the tokens into regexps.
225
+  var matches = new Array(tokens.length)
226
+
227
+  // Compile all the patterns before compilation.
228
+  for (var i = 0; i < tokens.length; i++) {
229
+    if (typeof tokens[i] === 'object') {
230
+      matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$')
231
+    }
232
+  }
233
+
234
+  return function (data, options) {
235
+    var path = ''
236
+    var encode = (options && options.encode) || encodeURIComponent
237
+
238
+    for (var i = 0; i < tokens.length; i++) {
239
+      var token = tokens[i]
240
+
241
+      if (typeof token === 'string') {
242
+        path += token
243
+        continue
244
+      }
245
+
246
+      var value = data ? data[token.name] : undefined
247
+      var segment
248
+
249
+      if (Array.isArray(value)) {
250
+        if (!token.repeat) {
251
+          throw new TypeError('Expected "' + token.name + '" to not repeat, but got array')
252
+        }
253
+
254
+        if (value.length === 0) {
255
+          if (token.optional) continue
256
+
257
+          throw new TypeError('Expected "' + token.name + '" to not be empty')
258
+        }
259
+
260
+        for (var j = 0; j < value.length; j++) {
261
+          segment = encode(value[j], token)
262
+
263
+          if (!matches[i].test(segment)) {
264
+            throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '"')
265
+          }
266
+
267
+          path += (j === 0 ? token.prefix : token.delimiter) + segment
268
+        }
269
+
270
+        continue
271
+      }
272
+
273
+      if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
274
+        segment = encode(String(value), token)
275
+
276
+        if (!matches[i].test(segment)) {
277
+          throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"')
278
+        }
279
+
280
+        path += token.prefix + segment
281
+        continue
282
+      }
283
+
284
+      if (token.optional) continue
285
+
286
+      throw new TypeError('Expected "' + token.name + '" to be ' + (token.repeat ? 'an array' : 'a string'))
287
+    }
288
+
289
+    return path
290
+  }
291
+}
292
+
293
+/**
294
+ * Escape a regular expression string.
295
+ *
296
+ * @param  {string} str
297
+ * @return {string}
298
+ */
299
+function escapeString (str) {
300
+  return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1')
301
+}
302
+
303
+/**
304
+ * Escape the capturing group by escaping special characters and meaning.
305
+ *
306
+ * @param  {string} group
307
+ * @return {string}
308
+ */
309
+function escapeGroup (group) {
310
+  return group.replace(/([=!:$/()])/g, '\\$1')
311
+}
312
+
313
+/**
314
+ * Get the flags for a regexp from the options.
315
+ *
316
+ * @param  {Object} options
317
+ * @return {string}
318
+ */
319
+function flags (options) {
320
+  return options && options.sensitive ? '' : 'i'
321
+}
322
+
323
+/**
324
+ * Pull out keys from a regexp.
325
+ *
326
+ * @param  {!RegExp} path
327
+ * @param  {Array=}  keys
328
+ * @return {!RegExp}
329
+ */
330
+function regexpToRegexp (path, keys) {
331
+  if (!keys) return path
332
+
333
+  // Use a negative lookahead to match only capturing groups.
334
+  var groups = path.source.match(/\((?!\?)/g)
335
+
336
+  if (groups) {
337
+    for (var i = 0; i < groups.length; i++) {
338
+      keys.push({
339
+        name: i,
340
+        prefix: null,
341
+        delimiter: null,
342
+        optional: false,
343
+        repeat: false,
344
+        pattern: null
345
+      })
346
+    }
347
+  }
348
+
349
+  return path
350
+}
351
+
352
+/**
353
+ * Transform an array into a regexp.
354
+ *
355
+ * @param  {!Array}  path
356
+ * @param  {Array=}  keys
357
+ * @param  {Object=} options
358
+ * @return {!RegExp}
359
+ */
360
+function arrayToRegexp (path, keys, options) {
361
+  var parts = []
362
+
363
+  for (var i = 0; i < path.length; i++) {
364
+    parts.push(pathToRegexp(path[i], keys, options).source)
365
+  }
366
+
367
+  return new RegExp('(?:' + parts.join('|') + ')', flags(options))
368
+}
369
+
370
+/**
371
+ * Create a path regexp from string input.
372
+ *
373
+ * @param  {string}  path
374
+ * @param  {Array=}  keys
375
+ * @param  {Object=} options
376
+ * @return {!RegExp}
377
+ */
378
+function stringToRegexp (path, keys, options) {
379
+  return tokensToRegExp(parse(path, options), keys, options)
380
+}
381
+
382
+/**
383
+ * Expose a function for taking tokens and returning a RegExp.
384
+ *
385
+ * @param  {!Array}  tokens
386
+ * @param  {Array=}  keys
387
+ * @param  {Object=} options
388
+ * @return {!RegExp}
389
+ */
390
+function tokensToRegExp (tokens, keys, options) {
391
+  options = options || {}
392
+
393
+  var strict = options.strict
394
+  var start = options.start !== false
395
+  var end = options.end !== false
396
+  var delimiter = options.delimiter || DEFAULT_DELIMITER
397
+  var endsWith = [].concat(options.endsWith || []).map(escapeString).concat('$').join('|')
398
+  var route = start ? '^' : ''
399
+
400
+  // Iterate over the tokens and create our regexp string.
401
+  for (var i = 0; i < tokens.length; i++) {
402
+    var token = tokens[i]
403
+
404
+    if (typeof token === 'string') {
405
+      route += escapeString(token)
406
+    } else {
407
+      var capture = token.repeat
408
+        ? '(?:' + token.pattern + ')(?:' + escapeString(token.delimiter) + '(?:' + token.pattern + '))*'
409
+        : token.pattern
410
+
411
+      if (keys) keys.push(token)
412
+
413
+      if (token.optional) {
414
+        if (!token.prefix) {
415
+          route += '(' + capture + ')?'
416
+        } else {
417
+          route += '(?:' + escapeString(token.prefix) + '(' + capture + '))?'
418
+        }
419
+      } else {
420
+        route += escapeString(token.prefix) + '(' + capture + ')'
421
+      }
422
+    }
423
+  }
424
+
425
+  if (end) {
426
+    if (!strict) route += '(?:' + escapeString(delimiter) + ')?'
427
+
428
+    route += endsWith === '$' ? '$' : '(?=' + endsWith + ')'
429
+  } else {
430
+    var endToken = tokens[tokens.length - 1]
431
+    var isEndDelimited = typeof endToken === 'string'
432
+      ? endToken[endToken.length - 1] === delimiter
433
+      : endToken === undefined
434
+
435
+    if (!strict) route += '(?:' + escapeString(delimiter) + '(?=' + endsWith + '))?'
436
+    if (!isEndDelimited) route += '(?=' + escapeString(delimiter) + '|' + endsWith + ')'
437
+  }
438
+
439
+  return new RegExp(route, flags(options))
440
+}
441
+
442
+/**
443
+ * Normalize the given path string, returning a regular expression.
444
+ *
445
+ * An empty array can be passed in for the keys, which will hold the
446
+ * placeholder key descriptions. For example, using `/user/:id`, `keys` will
447
+ * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
448
+ *
449
+ * @param  {(string|RegExp|Array)} path
450
+ * @param  {Array=}                keys
451
+ * @param  {Object=}               options
452
+ * @return {!RegExp}
453
+ */
454
+function pathToRegexp (path, keys, options) {
455
+  if (path instanceof RegExp) {
456
+    return regexpToRegexp(path, keys)
457
+  }
458
+
459
+  if (Array.isArray(path)) {
460
+    return arrayToRegexp(/** @type {!Array} */ (path), keys, options)
461
+  }
462
+
463
+  return stringToRegexp(/** @type {string} */ (path), keys, options)
464
+}
465
+
466
+
467
+/***/ }),
468
+
469
+/***/ "./src/creat-route-map.ts":
470
+/*!********************************!*\
471
+  !*** ./src/creat-route-map.ts ***!
472
+  \********************************/
473
+/*! no static exports found */
474
+/***/ (function(module, exports, __webpack_require__) {
475
+
476
+"use strict";
477
+
478
+var __values = (this && this.__values) || function (o) {
479
+    var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
480
+    if (m) return m.call(o);
481
+    return {
482
+        next: function () {
483
+            if (o && i >= o.length) o = void 0;
484
+            return { value: o && o[i++], done: !o };
485
+        }
486
+    };
487
+};
488
+var __importDefault = (this && this.__importDefault) || function (mod) {
489
+    return (mod && mod.__esModule) ? mod : { "default": mod };
490
+};
491
+Object.defineProperty(exports, "__esModule", { value: true });
492
+var path_to_regexp_1 = __importDefault(__webpack_require__(/*! path-to-regexp */ "./node_modules/path-to-regexp/index.js"));
493
+var path_1 = __webpack_require__(/*! ./utils/path */ "./src/utils/path.ts");
494
+function default_1(routes) {
495
+    var e_1, _a;
496
+    var routeMap = new Map();
497
+    try {
498
+        for (var routes_1 = __values(routes), routes_1_1 = routes_1.next(); !routes_1_1.done; routes_1_1 = routes_1.next()) {
499
+            var $route = routes_1_1.value;
500
+            createRouteRecoed($route);
501
+        }
502
+    }
503
+    catch (e_1_1) { e_1 = { error: e_1_1 }; }
504
+    finally {
505
+        try {
506
+            if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
507
+        }
508
+        finally { if (e_1) throw e_1.error; }
509
+    }
510
+    return routeMap;
511
+    //递归遍历,编写路由定义时确保*在最后一个
512
+    function createRouteRecoed(route, parent) {
513
+        var keys = [];
514
+        var path = path_1.normalizePath(route.path, parent);
515
+        var componentName = route.component;
516
+        var regex = path_to_regexp_1.default(path, keys);
517
+        var record = {
518
+            abstract: !!route.abstract,
519
+            path: path,
520
+            componentName: componentName,
521
+            regex: regex,
522
+            paramsName: keys.filter(function (key) { return !key.optional; }).map(function (key) { return key.name; })
523
+        };
524
+        if (parent)
525
+            record.parentPath = parent.path;
526
+        if (parent)
527
+            record.parent = parent;
528
+        routeMap.set(path, record);
529
+        if (route.children) {
530
+            record.children=route.children.map(function ($route) { return createRouteRecoed($route, record); });
531
+        }
532
+        return record;
533
+    }
534
+}
535
+exports.default = default_1;
536
+
537
+
538
+/***/ }),
539
+
540
+/***/ "./src/get-match.ts":
541
+/*!**************************!*\
542
+  !*** ./src/get-match.ts ***!
543
+  \**************************/
544
+/*! no static exports found */
545
+/***/ (function(module, exports, __webpack_require__) {
546
+
547
+"use strict";
548
+
549
+var __values = (this && this.__values) || function (o) {
550
+    var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
551
+    if (m) return m.call(o);
552
+    return {
553
+        next: function () {
554
+            if (o && i >= o.length) o = void 0;
555
+            return { value: o && o[i++], done: !o };
556
+        }
557
+    };
558
+};
559
+Object.defineProperty(exports, "__esModule", { value: true });
560
+function matchRecord(path, routeRecord) {
561
+    var e_1, _a;
562
+    try {
563
+        for (var _b = __values(routeRecord.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
564
+            let paramPath = path;
565
+            var record = _c.value;
566
+            if (paramPath.split('/').length < record.path.split('/').length) {
567
+                paramPath += '/0';
568
+            }
569
+            var matchVal = record.regex.exec(paramPath);
570
+            if (matchVal) {
571
+                var params = {};
572
+                var componentNameList = getComponentNameList(record);
573
+                for (var i = 0; i < record.paramsName.length; i++) {
574
+                    params[record.paramsName[i]] = matchVal[i + 1];
575
+                }
576
+                return { params: params, componentNameList: componentNameList, path: path,record:record };
577
+            }
578
+        }
579
+    }
580
+    catch (e_1_1) { e_1 = { error: e_1_1 }; }
581
+    finally {
582
+        try {
583
+            if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
584
+        }
585
+        finally { if (e_1) throw e_1.error; }
586
+    }
587
+}
588
+exports.matchRecord = matchRecord;
589
+function getComponentNameList(record) {
590
+    var componentNameList = [];
591
+    recursiveRecord(record);
592
+    return componentNameList;
593
+    function recursiveRecord(record) {
594
+        if (record.componentName) {
595
+            componentNameList.unshift(record.componentName);
596
+        }
597
+        if (record.parent)
598
+            recursiveRecord(record.parent);
599
+    }
600
+}
601
+
602
+
603
+/***/ }),
604
+
605
+/***/ "./src/index.ts":
606
+/*!**********************!*\
607
+  !*** ./src/index.ts ***!
608
+  \**********************/
609
+/*! no static exports found */
610
+/***/ (function(module, exports, __webpack_require__) {
611
+
612
+"use strict";
613
+
614
+var __importDefault = (this && this.__importDefault) || function (mod) {
615
+    return (mod && mod.__esModule) ? mod : { "default": mod };
616
+};
617
+Object.defineProperty(exports, "__esModule", { value: true });
618
+var warn_1 = __webpack_require__(/*! ./utils/warn */ "./src/utils/warn.ts");
619
+var const_1 = __webpack_require__(/*! ./utils/const */ "./src/utils/const.ts");
620
+var router_1 = __importDefault(__webpack_require__(/*! ./router */ "./src/router.ts"));
621
+function default_1(config) {
622
+    if (!this)
623
+        warn_1.error('this is not found');
624
+    var __router = new router_1.default(config);
625
+    var namespace = '$router';
626
+    if (config && config.option && config.option.namespace) {
627
+        namespace = config.option.namespace;
628
+    }
629
+    this[namespace] = {
630
+        get currentPath() {
631
+            return __router.currentPath;
632
+        },
633
+        get params() {
634
+            return __router.params;
635
+        },
636
+        //方法
637
+        get push() {
638
+            return __router.push.bind(__router);
639
+        },
640
+        get replace() {
641
+            return __router.replace.bind(__router);
642
+        },
643
+        get setBeforeChange() {
644
+            return __router.setBeforeChange.bind(__router);
645
+        },
646
+        get setAfterChange() {
647
+            return __router.setAfterChange.bind(__router);
648
+        },
649
+        get addParamsListener() {
650
+            return __router.addParamsListener.bind(__router);
651
+        },
652
+        get removeParamsListener() {
653
+            return __router.removeParamsListener.bind(__router);
654
+        },
655
+    };
656
+    this[const_1.mountName] = __router;
657
+}
658
+exports.default = default_1;
659
+
660
+
661
+/***/ }),
662
+
663
+/***/ "./src/router.ts":
664
+/*!***********************!*\
665
+  !*** ./src/router.ts ***!
666
+  \***********************/
667
+/*! no static exports found */
668
+/***/ (function(module, exports, __webpack_require__) {
669
+
670
+"use strict";
671
+
672
+var __values = (this && this.__values) || function (o) {
673
+    var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
674
+    if (m) return m.call(o);
675
+    return {
676
+        next: function () {
677
+            if (o && i >= o.length) o = void 0;
678
+            return { value: o && o[i++], done: !o };
679
+        }
680
+    };
681
+};
682
+var __read = (this && this.__read) || function (o, n) {
683
+    var m = typeof Symbol === "function" && o[Symbol.iterator];
684
+    if (!m) return o;
685
+    var i = m.call(o), r, ar = [], e;
686
+    try {
687
+        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
688
+    }
689
+    catch (error) { e = { error: error }; }
690
+    finally {
691
+        try {
692
+            if (r && !r.done && (m = i["return"])) m.call(i);
693
+        }
694
+        finally { if (e) throw e.error; }
695
+    }
696
+    return ar;
697
+};
698
+var __importDefault = (this && this.__importDefault) || function (mod) {
699
+    return (mod && mod.__esModule) ? mod : { "default": mod };
700
+};
701
+Object.defineProperty(exports, "__esModule", { value: true });
702
+var warn_1 = __webpack_require__(/*! ./utils/warn */ "./src/utils/warn.ts");
703
+var creat_route_map_1 = __importDefault(__webpack_require__(/*! ./creat-route-map */ "./src/creat-route-map.ts"));
704
+var get_match_1 = __webpack_require__(/*! ./get-match */ "./src/get-match.ts");
705
+var Router = /** @class */ (function () {
706
+
707
+    function Router(config) {
708
+
709
+        if (config === void 0) { config = {}; }
710
+        this.histry = [];
711
+        this.registerComponents = new Map();
712
+        this.routeRecord = new Map();
713
+        this.waitCallComponents = [];
714
+        this.onParamsHooks = new Map();
715
+        this.__beforePathChange = null;
716
+        this.__afterPathChange = null;
717
+        this.currentPath = '';
718
+        this.params = {};
719
+        this.query = {};
720
+        if (!config.routes)
721
+            warn_1.error('not found routes in config');
722
+        this.routeRecord = creat_route_map_1.default(config.routes);
723
+        //不设置初始initPath的话,默认为 /
724
+        var initPath = '/';
725
+        if (config.option && config.option.initPath)
726
+            initPath = config.option.initPath;
727
+        this.push(initPath);
728
+    }
729
+    Router.prototype.__matchrouteRecord = function (path) {
730
+        var e_1, _a;
731
+        var result = get_match_1.matchRecord(path, this.routeRecord);
732
+        //没有匹配到路由
733
+        if (!result) {
734
+            this.__clearComponentName();
735
+            return;
736
+        }
737
+        this.waitCallComponents = result.componentNameList;
738
+        try {
739
+            //触发router-view变化
740
+            for (var _b = __values(this.registerComponents.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
741
+                var com = _c.value;
742
+                var oldName = com.data.name;
743
+                var newName = this.waitCallComponents.shift();
744
+                com.setData({ name: newName });
745
+                if (oldName !== newName)
746
+                    break;
747
+            }
748
+        }
749
+        catch (e_1_1) { e_1 = { error: e_1_1 }; }
750
+        finally {
751
+            try {
752
+                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
753
+            }
754
+            finally { if (e_1) throw e_1.error; }
755
+        }
756
+        this.currentPath = result.path;
757
+        //触发路由参数变化
758
+        this.__setParams(result.params);
759
+    };
760
+    Router.prototype.__clearComponentName = function () {
761
+        var e_2, _a;
762
+        if (this.registerComponents.size > 0) {
763
+            try {
764
+                for (var _b = __values(this.registerComponents.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
765
+                    var _com = _c.value;
766
+                    _com.setData({ name: null });
767
+                    break;
768
+                }
769
+            }
770
+            catch (e_2_1) { e_2 = { error: e_2_1 }; }
771
+            finally {
772
+                try {
773
+                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
774
+                }
775
+                finally { if (e_2) throw e_2.error; }
776
+            }
777
+        }
778
+        this.currentPath = '';
779
+        this.__setParams(Object.create(null));
780
+    };
781
+    Router.prototype.__invokeBeforeHooks = function (nextPath) {
782
+        if (this.__beforePathChange === null)
783
+            return true;
784
+        return this.__beforePathChange(this.currentPath, nextPath);
785
+    };
786
+    Router.prototype.__invokeAfterHooks = function () {
787
+        if (this.__afterPathChange === null)
788
+            return true;
789
+        return this.__afterPathChange();
790
+    };
791
+    Router.prototype.__setCurrentPath = function (path) {
792
+        this.currentPath = path;
793
+    };
794
+    Router.prototype.__setParams = function (params) {
795
+        var e_3, _a;
796
+        var oldParams = this.params;
797
+        this.params = params;
798
+        try {
799
+            for (var _b = __values(this.onParamsHooks.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
800
+                var _d = __read(_c.value, 2), com = _d[0], methodName = _d[1];
801
+                if (com)
802
+                    com[methodName](oldParams, params);
803
+            }
804
+        }
805
+        catch (e_3_1) { e_3 = { error: e_3_1 }; }
806
+        finally {
807
+            try {
808
+                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
809
+            }
810
+            finally { if (e_3) throw e_3.error; }
811
+        }
812
+    };
813
+    Router.prototype.registerComponent = function (_this) {
814
+        var $id = _this.$id;
815
+        if (this.waitCallComponents.length > 0)
816
+            _this.setData({ name: this.waitCallComponents.shift() });
817
+        this.registerComponents.set($id, _this);
818
+    };
819
+    Router.prototype.removeComponent = function (_this) {
820
+        var $id = _this.$id;
821
+        var success = this.registerComponents.delete($id);
822
+        if (!success)
823
+            warn_1.warn('delete router-view fail');
824
+    };
825
+    Router.prototype.go = function (n) { };
826
+    Router.prototype.push = function (path) {
827
+        if (!this.__invokeBeforeHooks(path))
828
+            return;
829
+        path = this.getPathForAbstract(path);
830
+        this.__matchrouteRecord(path);
831
+        this.histry.push(path);
832
+        this.__setCurrentPath(path);
833
+        this.__invokeAfterHooks && this.__invokeAfterHooks();
834
+    };
835
+
836
+    Router.prototype.replace = function (path) {
837
+        if (!this.__invokeBeforeHooks(path))
838
+            return;
839
+        path = this.getPathForAbstract(path);
840
+        this.__matchrouteRecord(path);
841
+        this.histry.pop();
842
+        this.histry.push(path);
843
+        this.__setCurrentPath(path);
844
+        this.__invokeAfterHooks && this.__invokeAfterHooks();
845
+    };
846
+    Router.prototype.getPathForAbstract = function (path) {
847
+        let result = get_match_1.matchRecord(path, this.routeRecord);
848
+        if (!result) {
849
+            debugger;
850
+        }
851
+        let record = result.record;
852
+
853
+        if (record.abstract == true && record.children && record.children.length) {
854
+            let defaultChild = record.children.find(item => item.default);
855
+            if (!defaultChild) {
856
+                defaultChild = record.children[0];
857
+            }
858
+            path = path.replace(new RegExp("^" + record.path), defaultChild.path);
859
+            return path;
860
+        }
861
+        return path;
862
+    };
863
+    Router.prototype.setBeforeChange = function (_this, methodName) {
864
+        if (_this === null) {
865
+            this.__beforePathChange = null;
866
+            return;
867
+        }
868
+        if (_this[methodName] instanceof Function) {
869
+            this.__beforePathChange = _this[methodName].bind(_this);
870
+        }
871
+    };
872
+    Router.prototype.setAfterChange = function (_this, methodName) {
873
+        if (_this === null) {
874
+            this.__afterPathChange = null;
875
+            return;
876
+        }
877
+        if (_this[methodName] instanceof Function) {
878
+            this.__afterPathChange = _this[methodName].bind(_this);
879
+        }
880
+    };
881
+    Router.prototype.addParamsListener = function (_this, methodName) {
882
+        if (_this[methodName] instanceof Function) {
883
+            this.onParamsHooks.set(_this, methodName);
884
+            return;
885
+        }
886
+        warn_1.warn(_this.is + ": can't found methor [" + methodName + "]");
887
+    };
888
+    Router.prototype.removeParamsListener = function (_this) {
889
+        this.onParamsHooks.delete(_this);
890
+    };
891
+
892
+    return Router;
893
+}());
894
+exports.default = Router;
895
+
896
+
897
+/***/ }),
898
+
899
+/***/ "./src/utils/const.ts":
900
+/*!****************************!*\
901
+  !*** ./src/utils/const.ts ***!
902
+  \****************************/
903
+/*! no static exports found */
904
+/***/ (function(module, exports, __webpack_require__) {
905
+
906
+"use strict";
907
+
908
+Object.defineProperty(exports, "__esModule", { value: true });
909
+exports.mountName = '__routerInstance';
910
+
911
+
912
+/***/ }),
913
+
914
+/***/ "./src/utils/path.ts":
915
+/*!***************************!*\
916
+  !*** ./src/utils/path.ts ***!
917
+  \***************************/
918
+/*! no static exports found */
919
+/***/ (function(module, exports, __webpack_require__) {
920
+
921
+"use strict";
922
+
923
+Object.defineProperty(exports, "__esModule", { value: true });
924
+function cleanPath(path) {
925
+    return path.replace(/\/\//g, '/');
926
+}
927
+exports.cleanPath = cleanPath;
928
+function normalizePath(path, parent) {
929
+    if (!parent)
930
+        return path;
931
+    return cleanPath(parent.path + "/" + path);
932
+}
933
+exports.normalizePath = normalizePath;
934
+
935
+
936
+/***/ }),
937
+
938
+/***/ "./src/utils/warn.ts":
939
+/*!***************************!*\
940
+  !*** ./src/utils/warn.ts ***!
941
+  \***************************/
942
+/*! no static exports found */
943
+/***/ (function(module, exports, __webpack_require__) {
944
+
945
+"use strict";
946
+
947
+Object.defineProperty(exports, "__esModule", { value: true });
948
+function error(message) {
949
+    throw new Error("[miniapp-router] " + message);
950
+}
951
+exports.error = error;
952
+function warn(message) {
953
+    console.warn("[miniapp-router] " + message);
954
+}
955
+exports.warn = warn;
956
+
957
+
958
+/***/ })
959
+
960
+/******/ });
961
+//# sourceMappingURL=router.js.map

+ 36
- 0
src/components/miniapp-router/package.json View File

@@ -0,0 +1,36 @@
1
+{
2
+  "name": "miniapp-router",
3
+  "version": "0.1.6",
4
+  "description": "miniapp for taobao",
5
+  "author": "melonzhang",
6
+  "devDependencies": {
7
+    "@types/jest": "^24.0.15",
8
+    "@types/lodash": "^4.14.132",
9
+    "@types/path-to-regexp": "^1.7.0",
10
+    "jest": "^24.8.0",
11
+    "lodash": "^4.17.11",
12
+    "path-to-regexp": "^3.0.0",
13
+    "ts-jest": "^24.0.2",
14
+    "ts-loader": "^6.0.2",
15
+    "typescript": "^3.5.1",
16
+    "webpack-bundle-analyzer": "^3.3.2"
17
+  },
18
+  "main": "lib/router.js",
19
+  "scripts": {
20
+    "prepublish": "npm run test && npm run build",
21
+    "build-dev": "webpack --env.NODE_ENV=development --watch",
22
+    "build": "webpack --env.NODE_ENV=development",
23
+    "test": "jest"
24
+  },
25
+  "files": [
26
+    "lib",
27
+    "router-view",
28
+    "demo"
29
+  ],
30
+  "publishConfig": {
31
+    "registry": "https://registry.npmjs.org/"
32
+  },
33
+  "__npminstall_done": "Thu Oct 31 2019 20:22:50 GMT+0800 (GMT+08:00)",
34
+  "_from": "miniapp-router@0.1.6",
35
+  "_resolved": "https://registry.npm.taobao.org/miniapp-router/download/miniapp-router-0.1.6.tgz"
36
+}

+ 0
- 0
src/components/miniapp-router/router-view/router-view.acss View File


+ 3
- 0
src/components/miniapp-router/router-view/router-view.axml View File

@@ -0,0 +1,3 @@
1
+<view style="height:100%">
2
+  HI, My Component222
3
+</view>

+ 18
- 0
src/components/miniapp-router/router-view/router-view.js View File

@@ -0,0 +1,18 @@
1
+Component({
2
+  mixins: [],
3
+  data: {
4
+    name: '',
5
+    query: {},
6
+    params: {},
7
+  },
8
+  props: {},
9
+  didMount: function() {
10
+    if (!this.$page.__routerInstance)
11
+      throw new Error('[miniapp-router] routerInstance not found');
12
+    this.$page.__routerInstance.registerComponent(this);
13
+  },
14
+  didUnmount: function() {
15
+    this.$page.__routerInstance.removeComponent(this);
16
+  },
17
+  methods: {},
18
+});

+ 3
- 0
src/components/miniapp-router/router-view/router-view.json View File

@@ -0,0 +1,3 @@
1
+{
2
+  "component": true
3
+}

+ 19
- 0
src/index.html View File

@@ -0,0 +1,19 @@
1
+<!DOCTYPE html>
2
+<html>
3
+<head>
4
+  <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
5
+  <meta content="width=device-width,initial-scale=1,user-scalable=no" name="viewport">
6
+  <meta name="apple-mobile-web-app-capable" content="yes">
7
+  <meta name="apple-touch-fullscreen" content="yes">
8
+  <meta name="format-detection" content="telephone=no,address=no">
9
+  <meta name="apple-mobile-web-app-status-bar-style" content="white">
10
+  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" >
11
+  <title></title>
12
+  <script>
13
+    !function(x){function w(){var v,u,t,tes,s=x.document,r=s.documentElement,a=r.getBoundingClientRect().width;if(!v&&!u){var n=!!x.navigator.appVersion.match(/AppleWebKit.*Mobile.*/);v=x.devicePixelRatio;tes=x.devicePixelRatio;v=n?v:1,u=1/v}if(a>=640){r.style.fontSize="40px"}else{if(a<=320){r.style.fontSize="20px"}else{r.style.fontSize=a/320*20+"px"}}}x.addEventListener("resize",function(){w()});w()}(window);
14
+  </script>
15
+</head>
16
+<body>
17
+  <div id="app"></div>
18
+</body>
19
+</html>

+ 6
- 0
src/pages/index/index.config.js View File

@@ -0,0 +1,6 @@
1
+export default {
2
+  navigationBarTitleText: '首页',
3
+  usingComponents: { 
4
+    'router-view': '../../components/miniapp-router/router-view/router-view', // 书写第三方组件的相对路径
5
+  },
6
+}

+ 28
- 0
src/pages/index/index.jsx View File

@@ -0,0 +1,28 @@
1
+import React, { Component } from 'react'
2
+import { View, Text } from '@tarojs/components'
3
+import './index.scss'
4
+
5
+export default class Index extends Component {
6
+
7
+  componentWillMount () { }
8
+
9
+  componentDidMount () { }
10
+
11
+  componentWillUnmount () { }
12
+
13
+  componentDidShow () { }
14
+
15
+  componentDidHide () { }
16
+
17
+  render () {
18
+    return (
19
+      <View className='index'>
20
+        <Text>Hello world!</Text>
21
+        <router-view />
22
+        <router-view>
23
+          <view>im inside</view>
24
+        </router-view>
25
+      </View>
26
+    )
27
+  }
28
+}

+ 0
- 0
src/pages/index/index.scss View File


+ 10514
- 0
yarn.lock
File diff suppressed because it is too large
View File