Commit 784f5ab6 by liimin

init

0 parents
{
"presets": [["env", { "modules": false }], "stage-2", "flow"],
"plugins": ["transform-runtime"],
"env": {
"test": {
"presets": [["env"], "stage-2", "flow"]
}
}
}
'use strict';
module.exports = {
extends: [
'cz'
],
rules: {
}
};
'use strict';
module.exports = {
types: [
{
value: 'WIP',
name : '💪 WIP: Work in progress'
},
{
value: 'feat',
name : '✨ feat: A new feature'
},
{
value: 'fix',
name : '🐞 fix: A bug fix'
},
{
value: 'refactor',
name : '🛠 refactor: A code change that neither fixes a bug nor adds a feature'
},
{
value: 'docs',
name : '📚 docs: Documentation only changes'
},
{
value: 'test',
name : '🏁 test: Add missing tests or correcting existing tests'
},
{
value: 'chore',
name : '🗯 chore: Changes that don\'t modify src or test files. Such as updating build tasks, package manager'
},
{
value: 'style',
name : '💅 style: Code Style, Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)'
},
{
value: 'revert',
name : '⏪ revert: Revert to a commit'
}
],
scopes: [],
allowCustomScopes: true,
allowBreakingChanges: ["feat", "fix"]
};
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
build/*.js
dist/*.js
temp/*.js
examples/*.js
rollup.config.*.js
module.exports = {
// extends: ['airbnb-base', 'plugin:flowtype/recommended', 'prettier'],
extends: ['plugin:flowtype/recommended', 'prettier'],
plugins: ['flowtype'],
env: {
browser: true,
node: true,
es6: true,
commonjs: true,
jest: true
},
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module',
allowImportExportEverywhere: true
},
rules: {
'class-methods-use-this': 'off',
'comma-dangle': 'off',
'global-require': 'off',
'import/no-extraneous-dependencies': 'off',
'import/prefer-default-export': 'off',
'max-len': 'off',
'no-underscore-dangle': 'off'
}
}
[ignore]
.*/node_modules/.*
.*/test/.*
.*/scripts/.*
.*/examples/.*
[include]
[libs]
[lints]
[options]
module.file_ext=.js
module.file_ext=.jsx
module.file_ext=.json
[strict]
# General
.DS_Store
.AppleDouble
.LSOverride
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# Logs
logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# Editor directories and files
.idea
.vscode
# Dependency directories
node_modules
# Optional
.npm
.node_repl_history
# assets publish
# you can ignore dist Folder if you publish your assets with CI to CDN
# Project specific stuff
temp
typings
{
"printWidth": 800,
"tabWidth": 2,
"singleQuote": true,
"trailingComma": "none",
"semi": false,
"wrap_line_length": 820,
"wrap_attributes": "auto",
"proseWrap": "always",
"arrowParens": "avoid",
"bracketSpacing": true,
"htmlWhitespaceSensitivity": "ignore",
"javascript.format.insertSpaceBeforeFunctionParenthesis": true,
"jsxBracketSameLine": true,
"files.insertFinalNewline": true,
"useTabs": false,
"eslintIntegration": true,
"overrides": [
{
"files": ".prettierrc",
"options": {
"parser": "json"
}
}
],
"endOfLine": "auto"
}
anguage: node_js
node_js:
- 8.9.3
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<a name="0.2.0"></a>
# [0.2.0](https://github.com/leohxj/rollup-starter-kit/compare/0.1.0-canary.1...0.2.0) (2018-03-04)
### Features
* add DEVELOPMENT debug log ([875c42c](https://github.com/leohxj/rollup-starter-kit/commit/875c42c))
* rename common.js -> cjs.js ([238c519](https://github.com/leohxj/rollup-starter-kit/commit/238c519))
* update year ([86827e3](https://github.com/leohxj/rollup-starter-kit/commit/86827e3))
<a name="0.1.0"></a>
# [0.1.0](https://github.com/leohxj/rollup-starter-kit/compare/0.1.0-canary.1...0.1.0) (2018-03-04)
### Features
* add DEVELOPMENT debug log ([875c42c](https://github.com/leohxj/rollup-starter-kit/commit/875c42c))
* rename common.js -> cjs.js ([238c519](https://github.com/leohxj/rollup-starter-kit/commit/238c519))
<a name="0.1.0"></a>
# 0.1.0 (2018-01-08)
### Features
* add commitizen ([ec81513](https://github.com/leohxj/rollup-starter-kit/commit/ec81513))
* update cz-config ([3d25491](https://github.com/leohxj/rollup-starter-kit/commit/3d25491))
* update cz-config ([7a69152](https://github.com/leohxj/rollup-starter-kit/commit/7a69152))
MIT License
Copyright (c) 2018 Leo Hui
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# a real scaffold for building library &middot; [![Author](https://img.shields.io/badge/Author-leohxj-blue.svg)](http://finalhome.org)
[中文 README](README.zh_CN.md)
# a real scaffold for building library &middot; [![Author](https://img.shields.io/badge/Author-leohxj-blue.svg)](http://finalhome.org)
[README in English](README.md)
## Tips
- package.json 中 配置 main, module, unpkg 指向 cjs, esm, umd 三个版本
- sourcemap, 应该在 development 版本中输出, 生产环境不需要, library 会被应用层再次打包, 由应用控制 sourcemap 的输出
- 生产环境
- umd: 一份压缩版本(.min)和未压缩版本(带有 sourcemap 吧?)
- 一份 commonjs 版本, 不需要压缩
- 一份 esm 版本, 不需要压缩
- cjs, esm 版本 如需有调试信息, 通过 process.env.NODE_ENV 区分
- jest: 设置 babelrc, 新增 env 配置, 因为 jest 无法识别 ES Module.
import tracker from '..'
describe('Group One', () => {
test('case-1', () => {
expect(tracker.foo(1)).toBe(3.14)
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>UMD Example</title>
</head>
<body>
<script src="../dist/gltracker.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
const element = document.createElement('h1')
element.innerHTML = gltracker.init
console.log(gltracker.init)
document.body.appendChild(element)
This diff could not be displayed because it is too large.
{
"name": "gltracker",
"version": "0.1.1",
"main": "dist/gltracker.min.js",
"module": "dist/gltracker.esm.js",
"unpkg": "dist/gltracker.min.js",
"keywords": [
"rollup",
"babel",
"starter"
],
"author": "limin",
"license": "MIT",
"scripts": {
"cz": "git-cz",
"clean": "rimraf dist",
"start": "npm run clean && cross-env NODE_ENV=development rollup -w -c scripts/rollup.config.dev.js",
"build": "npm run clean && cross-env NODE_ENV=production rollup -c scripts/rollup.config.prod.js",
"test": "npm run flow && jest",
"flow": "flow check",
"serve": "serve -p 8080",
"release": "standard-version"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -e $GIT_PARAMS"
}
},
"lint-staged": {
"src/**/*.js": [
"prettier --write",
"eslint --fix",
"git add"
]
},
"files": [
"src",
"dist/*.js"
],
"dependencies": {
"babel-runtime": "^6.26.0"
},
"devDependencies": {
"@commitlint/cli": "^5.2.8",
"@commitlint/config-conventional": "^5.2.3",
"babel-core": "^6.26.0",
"babel-eslint": "^8.1.2",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.1",
"babel-preset-flow": "^6.23.0",
"babel-preset-stage-2": "^6.24.1",
"commitizen": "^2.9.6",
"commitlint-config-cz": "^0.7.0",
"cross-env": "^5.1.3",
"cz-customizable": "^5.2.0",
"eslint": "^4.14.0",
"eslint-config-airbnb-base": "^12.1.0",
"eslint-config-prettier": "^2.9.0",
"eslint-plugin-flowtype": "^2.40.1",
"eslint-plugin-import": "^2.8.0",
"flow-bin": "^0.62.0",
"husky": "^0.15.0-beta.16",
"jest": "^22.0.4",
"lint-staged": "^6.0.0",
"prettier": "^1.9.2",
"rimraf": "^2.6.2",
"rollup": "^0.53.3",
"rollup-plugin-alias": "^1.4.0",
"rollup-plugin-babel": "^3.0.3",
"rollup-plugin-commonjs": "^8.2.6",
"rollup-plugin-eslint": "^4.0.0",
"rollup-plugin-filesize": "^1.5.0",
"rollup-plugin-node-resolve": "^3.0.0",
"rollup-plugin-replace": "^2.0.0",
"rollup-plugin-serve": "^0.4.2",
"rollup-plugin-uglify": "^2.0.1",
"serve": "^10.0.2",
"standard-version": "^4.3.0",
"uglify-es": "^3.3.4"
},
"config": {
"commitizen": {
"path": "node_modules/cz-customizable"
}
}
}
import alias from 'rollup-plugin-alias';
import eslint from 'rollup-plugin-eslint';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import replace from 'rollup-plugin-replace';
export default {
input: 'src/main.js',
plugins: [
alias({
resolve: ['.js']
}),
replace({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),
resolve(),
commonjs({
// non-CommonJS modules will be ignored, but you can also
// specifically include/exclude files
include: 'node_modules/**'
}),
eslint({
include: ['src/**/*.js']
}),
babel({
runtimeHelpers: true,
exclude: 'node_modules/**' // only transpile our source code
})
]
}
import baseConfig from './rollup.config.base';
import serve from 'rollup-plugin-serve';
import { name } from '../package.json';
export default {
...baseConfig,
output: [
{
file: `dist/${name}.js`,
format: 'umd',
name,
sourcemap: true
},
{
file: `dist/${name}.cjs.js`,
format: 'cjs',
name,
sourcemap: 'inline'
}
],
plugins: [
...baseConfig.plugins,
serve({
port: 8080,
contentBase: ['']
})
]
};
import filesize from 'rollup-plugin-filesize';
import uglify from 'rollup-plugin-uglify';
import { minify } from 'uglify-es';
import baseConfig from './rollup.config.base';
import { name, version, author } from '../package.json';
// banner
const banner =
`${'/*!\n' + ' * '}${name}.js v${version}\n` +
` * (c) 2018-${new Date().getFullYear()} ${author}\n` +
` * Released under the MIT License.\n` +
` */`;
// 支持输出 []
export default [
// .js, .cjs.js, .esm.js
{
...baseConfig,
output: [
// umd development version with sourcemap
{
file: `dist/${name}.js`,
format: 'umd',
name,
banner,
sourcemap: true
},
// cjs and esm version
{
file: `dist/${name}.cjs.js`,
format: 'cjs',
banner
},
// cjs and esm version
{
file: `dist/${name}.esm.js`,
format: 'es',
banner
}
],
plugins: [...baseConfig.plugins, filesize()]
},
// .min.js
{
...baseConfig,
output: [
// umd with compress version
{
file: `dist/${name}.min.js`,
format: 'umd',
name,
banner
}
],
plugins: [
...baseConfig.plugins,
uglify(
{
compress: {
drop_console: true
}
},
minify
),
filesize()
]
}
];
// **************配置开始***************** */
const STORAGE_PREPARE_DATA_KEY = 'tracker_prepare_data'
const kit = {}
const tracker = {}
const defaultData = {
server_url: 'http://tracking-backend.test.glsx.com/track',
send_timeout: 6000,
max_length: 10,
show_log: true
}
const commonData = {}
function init({ settings, common }) {
initSetting(settings)
setPublicProperties(common)
}
function initSetting(init = {}) {
Object.assign(defaultData, init)
}
//* **************配置结束***************** */
//* **************工具类***************** */
const util = {}
util.dateFormat = function(dateTime, format = 'YYYY-MM-DD HH:mm:ss') {
const date = new Date(dateTime)
const config = {
YYYY: date.getFullYear(),
MM: appendZero(date.getMonth() + 1), // getMonth() 方法根据本地时间返回指定日期的月份(从 0 到 11)
DD: appendZero(date.getDate()),
HH: appendZero(date.getHours()),
mm: appendZero(date.getMinutes()),
ss: appendZero(date.getSeconds())
}
for (const key in config) {
format = format.replace(key, config[key])
}
return format
}
function appendZero(int) {
if (int < 10) {
return '0' + `${int}`
}
return int
}
//* **************工具类***************** */
/** *********埋点store数据处理开始********* */
tracker.store = {
storageInfo: null,
store_queue: [],
getStorage() {
if (this.storageInfo) {
return this.storageInfo
}
this.storageInfo = getStorageSync(STORAGE_PREPARE_DATA_KEY) || ''
return this.storageInfo
},
mem: {
mdata: [],
getLength() {
return this.mdata.length
},
add(data) {
this.mdata.push(data)
},
clear(len) {
this.mdata.splice(0, len)
}
},
init() {
// 获取未上报的数据
const info = this.getStorage()
if (info) {
this.save(info)
}
},
save(info) {
setStorageSync(STORAGE_PREPARE_DATA_KEY, info)
}
}
/** *********埋点store数据处理结束********* */
/** *********控制台打印配置开始********* */
const logger = {}
logger.info = function() {
if (defaultData.show_log) {
if (typeof console === 'object' && console.log) {
try {
if (arguments.length === 3) {
return console.log(arguments[0], arguments[1], arguments[2])
}
if (arguments.length === 2) {
return console.log(arguments[0], arguments[1])
}
if (arguments.length === 1) {
return console.log(arguments[0])
}
} catch (e) {
console.log(arguments[0])
}
}
}
}
/** *********控制台打印配置结束********* */
/** *********上报接口请求开始********** */
const uploadStroageData = (params = {}, option) => {
const para = {
info: params
}
fetch(defaultData.server_url, {
method: 'post',
body: JSON.stringify(para),
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
})
.then(res => res.json())
.then(data => {
if (data.code == 200) {
option.success(option.len)
return
}
option.fail()
})
.catch(() => {
option.fail()
})
}
/** *********上报接口请求结束********** */
// 构建上报数据
// eslint-disable-next-line func-names
kit.buildData = function(trackParam) {
const data = {}
const temp = {
event: trackParam.event,
...trackParam.properties
}
if (trackParam.event == 'pv') {
const defaultTemp = {
intoTime: util.dateFormat(new Date()),
pageUrl: window.location.href,
...temp
}
Object.assign(data, defaultTemp)
setStorageSync('pageView', JSON.stringify(defaultTemp))
} else {
const s = getStorageSync('pageView') || null
temp.create_time = util.dateFormat(new Date())
data.exta = JSON.stringify(temp)
Object.assign(data, JSON.parse(s))
}
Object.assign(data, commonData)
return data
}
// 设置公共属性信息
function setPublicProperties(common = {}) {
Object.assign(commonData, common)
}
kit.processData = function(data) {
return data
}
// 批处理数据
kit.batchTrackData = function(data) {
return encodeTrackData(data)
}
// 格式化处理数据
function encodeTrackData(data) {
data = JSON.stringify(data)
return encodeURIComponent(data)
}
// 设置缓存数据
const setStorageSync = function(storage_key, value) {
const fn = function() {
localStorage.setItem(storage_key, encodeURIComponent(JSON.stringify(value)))
}
try {
fn()
} catch (error1) {
// console.log("set Storage fail --", error1);
logger.info('set Storage fail --', error1)
try {
fn()
} catch (error2) {
logger.info('set Storage fail again --', error2)
// console.log("set Storage fail again --", error2);
}
}
}
// 获取缓存数据
const getStorageSync = function(storage_key) {
let store = ''
try {
store = localStorage.getItem(storage_key)
} catch (e) {
try {
store = localStorage.getItem(storage_key)
} catch (e2) {
logger.info('getStorage fail')
}
}
store = JSON.parse(decodeURIComponent(store))
return store
}
const mergeStorageData = {}
mergeStorageData.getData = function(callback) {
const queue = getStorageSync(STORAGE_PREPARE_DATA_KEY)
mergeStorageData.deleteAesData(queue || [])
callback && callback()
}
mergeStorageData.deleteAesData = function(queue) {
const arr = []
const queue_len = queue.length
if (queue_len > 0) {
queue.forEach(item => {
arr.push(item)
})
}
tracker.store.mem.mdata = arr.concat(tracker.store.mem.mdata)
}
// 发送策略
var sendStrategy = {
dataHasSend: true,
dataHasChange: false,
syncStorage: false,
failTime: 0,
init() {
mergeStorageData.getData(sendStrategy.syncStorageState)
sendStrategy.batchInterval()
},
syncStorageState() {
sendStrategy.syncStorage = true
},
batchInterval() {
const _this = this
function loopWrite() {
setTimeout(() => {
_this.batchWrite()
loopWrite()
}, 500)
}
function loopSend() {
setTimeout(() => {
_this.batchSend()
loopSend()
}, defaultData.send_timeout * Math.pow(2, _this.failTime))
}
loopWrite()
loopSend()
},
is_first_batch_write: true,
batchWrite() {
const me = this
if (this.dataHasChange) {
if (this.is_first_batch_write) {
this.is_first_batch_write = false
setTimeout(() => {
me.batchSend()
}, 1000)
}
this.dataHasChange = false
if (this.syncStorage) {
setStorageSync(STORAGE_PREPARE_DATA_KEY, tracker.store.mem.mdata)
}
}
},
batchSend() {
if (this.dataHasSend) {
let data,
len,
mdata = tracker.store.mem.mdata
if (mdata.length >= 100) {
data = mdata.slice(0, 100)
} else {
data = mdata
}
len = data.length
if (len > 0) {
this.dataHasSend = false
this.webrequest({
data,
len,
success: this.batchRemove.bind(this),
fail: this.sendFail.bind(this)
})
}
}
},
batchRemove(len) {
tracker.store.mem.clear(len)
this.dataHasSend = true
this.dataHasChange = true
this.batchWrite()
this.failTime = 0
},
sendFail() {
this.dataHasSend = true
this.failTime++
},
webrequest(option) {
if (option.data.length > 0) {
const data = kit.batchTrackData(option.data)
logger.info('上报数据监控:', decodeURIComponent(data))
const temp = JSON.parse(decodeURIComponent(data))
uploadStroageData(temp, option)
} else {
option.success(option.len)
}
},
send(data) {
this.dataHasChange = true
if (tracker.store.mem.getLength() >= 500) {
logger.info('数据量存储过大,有异常')
tracker.store.mem.mdata.shift()
}
data = kit.processData(data)
if (data) {
tracker.store.mem.add(data)
}
if (tracker.store.mem.getLength() >= defaultData.max_length) {
this.batchSend()
}
}
}
// 发送事件
const trackEvent = {}
trackEvent.send = function(p) {
if (!defaultData.server_url) {
logger.info('error: server_url 不能为空')
return false
}
const data = tracker.kit.buildData(p)
if (data) {
sendStrategy.send(data)
} else {
logger.info('数据异常', data)
}
}
tracker.init = init
tracker.kit = kit
tracker.mergeStorageData = mergeStorageData
tracker.trackEvent = trackEvent
tracker.sendStrategy = sendStrategy
// eventType 事件类型 properties 业务对象 callback 回调
tracker.track = function(properties, eventType = 'click', callback) {
this.trackEvent.send(
{
type: 'track',
event: eventType,
properties
},
callback
)
}
// 启动初始化
{
tracker.store.init()
sendStrategy.init()
}
export default tracker
This diff could not be displayed because it is too large.
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!