Skip to content
This repository was archived by the owner on Nov 18, 2021. It is now read-only.

Commit 72dd3c7

Browse files
committed
使用 es6 的模块风格重构代码
1 parent 306e350 commit 72dd3c7

File tree

9 files changed

+3154
-132
lines changed

9 files changed

+3154
-132
lines changed

.eslintrc

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,12 @@
44
"ES6Promise": false,
55
"chromeCall": false
66
},
7+
"parserOptions": {
8+
"ecmaVersion": 6,
9+
"sourceType": "module"
10+
},
711
"env": {
8-
"browser": true,
9-
"amd": true,
12+
"node": true,
1013
"jasmine": true
1114
},
1215
"extends": [

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
/node_modules/
22
/coverage/
3+
/dist/

README.md

Lines changed: 49 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,53 @@
1-
# chrome call
1+
# chrome-call
22

33
[![Build Status](https://img.shields.io/travis/Selection-Translator/chrome-call/master.svg?style=flat-square)](https://travis-ci.org/Selection-Translator/chrome-call)
44
[![Coverage Status](https://img.shields.io/coveralls/Selection-Translator/chrome-call/master.svg?style=flat-square)](https://coveralls.io/github/Selection-Translator/chrome-call?branch=master)
55
[![dependencies Status](https://img.shields.io/david/Selection-Translator/chrome-call.svg?style=flat-square)](https://david-dm.org/Selection-Translator/chrome-call)
66
[![devDependencies Status](https://img.shields.io/david/dev/Selection-Translator/chrome-call.svg?style=flat-square)](https://david-dm.org/Selection-Translator/chrome-call?type=dev)
77
[![NPM Version](https://img.shields.io/npm/v/chrome-call.svg?style=flat-square)](https://www.npmjs.com/package/chrome-call)
88

9-
A really simple way to call the original chrome javascript API and return a Promise.
9+
Call the original chrome javascript API and return a Promise.
1010

1111
## Install
1212

13+
### Use with Webpack
14+
15+
If you build your project with webpack, then you can install chrome-call from npm:
16+
1317
```
14-
npm i -S chrome-call
18+
npm install chrome-call
19+
```
20+
21+
then you can import it in your project:
22+
23+
```js
24+
// es6
25+
import { call, scope } from 'chrome-call'
26+
27+
// commonjs
28+
const { call, scope } = require('chrome-call')
29+
```
30+
31+
### Use with <script>
32+
33+
Download chrome-call.js from [unpkg](https://unpkg.com/chrome-call)([min version](https://unpkg.com/chrome-call/dist/chrome-call.min.js)), then reference it in your html:
34+
35+
```html
36+
<script src="path/to/chrome-call.js"></script>
37+
<!-- now you will get a global variable named chromeCall -->
38+
<sciprt>
39+
var call = chromeCall.call
40+
var scope = chromeCall.scope
41+
</sciprt>
1542
```
1643

1744
## Usage
1845

1946
When you do:
2047

2148
```js
22-
var promise = new Promise(function (resolve, reject) {
23-
chrome.storage.local.get('key', function (items) {
49+
const promise = new Promise((resolve, reject) => {
50+
chrome.storage.local.get('key', items => {
2451
if(chrome.runtime.lastError){
2552
reject(chrome.runtime.lastError)
2653
} else {
@@ -33,7 +60,9 @@ var promise = new Promise(function (resolve, reject) {
3360
It's equal to:
3461

3562
```js
36-
var promise = chromeCall('storage.local.get', 'key')
63+
import { call } from 'chrome-call'
64+
65+
const promise = call('storage.local.get', 'key')
3766
```
3867

3968
That's really simple, right?
@@ -45,21 +74,28 @@ Most of chrome API only has zero or one argument in callback, but someone not, s
4574
In this situation, pass `true` as the first argument, then the value of promise will be an __real__ Array:
4675

4776
```js
48-
chromeCall(true, 'hid.receive', connectionId)
49-
.then(function (args) {
77+
import { call } from 'chrome-call'
78+
79+
call(true, 'hid.receive', connectionId)
80+
.then(args => {
5081
Array.isArray(args) // true
51-
var reportId = args[0]
52-
var data = args[1]
82+
const reportId = args[0]
83+
const data = args[1]
5384
})
5485
```
5586

5687
### Scope
5788

58-
The global `chromeCall` search function on `window.chrome`, but you can use different scope:
89+
The `call` method searches function on `window.chrome`, but you can use different scope:
5990

6091
```js
61-
var local = chromeCall.scope('storage.local') // or chromeCall.scope(chrome.storage.local)
62-
var promise = local('get', 'key')
92+
import { scope } from 'chrome-call'
93+
94+
const callLocal = scope('storage.local') // or scope(chrome.storage.local)
95+
const promise = callLocal('get', 'key')
96+
97+
const callHid = scope('hid') // or scope(chrome.hid)
98+
const promise2 = callHid(true, 'receive')
6399
```
64100

65101
## License

build/build.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
const path = require('path')
2+
const fs = require('fs-extra')
3+
4+
// 清空输出目录
5+
fs.emptyDirSync(path.resolve(__dirname, '../dist'))
6+
7+
// 编译 js
8+
const rollup = require('rollup')
9+
const buble = require('rollup-plugin-buble')
10+
const uglifyJS = require('uglify-js')
11+
const pkg = require('../package.json')
12+
13+
const banner = [
14+
'/*!',
15+
' * chrome-call v' + pkg.version,
16+
' * https://github.com/Selection-Translator/chrome-call',
17+
' * Released under the MIT License.',
18+
' */'
19+
].join('\n')
20+
21+
rollup.rollup({
22+
entry: path.resolve(__dirname, '../chrome-call.js'),
23+
plugins: [buble()]
24+
}).then(bundle => {
25+
// 输出 umd 格式
26+
const { code } = bundle.generate({
27+
format: 'umd',
28+
moduleName: 'chromeCall',
29+
banner
30+
})
31+
32+
fs.writeFile(path.resolve(__dirname, '../dist/chrome-call.js'), code)
33+
fs.writeFile(path.resolve(__dirname, '../dist/chrome-call.min.js'), uglifyJS.minify(code, { output: { comments: /^!/ } }).code)
34+
35+
// 输出 es 格式
36+
bundle.write({
37+
dest: path.resolve(__dirname, '../dist/chrome-call.esm.js'),
38+
format: 'es',
39+
banner
40+
})
41+
42+
// 输出 cjs 格式
43+
bundle.write({
44+
dest: path.resolve(__dirname, '../dist/chrome-call.common.js'),
45+
format: 'cjs',
46+
banner
47+
})
48+
})

chrome-call.js

Lines changed: 66 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -1,108 +1,81 @@
1-
(function (root, factory) {
2-
/* istanbul ignore next */
3-
if (typeof module === 'object' && typeof module.exports === 'object') {
4-
module.exports = factory()
5-
} else if (typeof define === 'function' && define.amd) {
6-
define([], factory)
7-
} else {
8-
root['chromeCall'] = factory()
9-
}
10-
})(this, function () {
11-
'use strict'
12-
var runtime = chrome.runtime
1+
const { runtime } = chrome
132

14-
/**
15-
* 根据 base 对象返回指定路径的栈
16-
* @param {String} path - 属性路径,可用点(.)分隔
17-
* @param {Object} base - 开始查找的那个对象
18-
* @returns {*[]}
19-
*
20-
* @example
21-
* pathStack('document.body',window) 应该返回 [window,window.document,window.document.body]
22-
*/
23-
function pathStack (path, base) {
24-
var keys = path.split('.')
25-
var stack = [base]
3+
/**
4+
* 根据 base 对象返回指定路径的栈
5+
* @param {String} path - 属性路径,可用点(.)分隔
6+
* @param {Object} base - 开始查找的那个对象
7+
* @returns {*[]}
8+
*
9+
* @example
10+
* pathStack('document.body',window) 应该返回 [window,window.document,window.document.body]
11+
*/
12+
function pathStack (path, base) {
13+
const keys = path.split('.')
14+
const stack = [base]
2615

27-
keys.forEach(function (key, i) {
28-
var val = stack[i][key]
29-
if (!val) {
30-
throw new Error('Cannot find "' + path + '".')
31-
}
32-
stack.push(val)
33-
})
16+
keys.forEach((key, i) => {
17+
const val = stack[i][key]
18+
if (!val) {
19+
throw new Error('Cannot find "' + path + '".')
20+
}
21+
stack.push(val)
22+
})
3423

35-
return stack
36-
}
24+
return stack
25+
}
26+
27+
/**
28+
* 根据基础对象返回一个函数,此函数会以基础对象为起点寻找指定属性并调用
29+
* @param {String|Object} base
30+
* @returns {Function}
31+
*/
32+
function scope (base) {
33+
const baseObj = typeof base === 'string' ? pathStack(base, chrome).pop() : base
3734

3835
/**
39-
* 根据基础对象返回一个函数,此函数会以基础对象为起点寻找指定属性并调用
40-
* @param {String|Object} base
41-
* @returns {Function}
36+
* 调用原本的 chrome api 并返回一个 Promise
37+
* @param {Boolean} [returnArray] - 当函数的第一个值是 true 时,则 Promise 会返回一个数组,包含 callback 的所有参数
38+
* @param {String} fnPath - 原本的 chrome api 的路径,相对于 chrome,如 storage.local.get
39+
* @returns {Promise}
4240
*/
43-
function scope (base) {
44-
var baseObj = typeof base === 'string' ? pathStack(base, chrome).pop() : base
45-
46-
/**
47-
* 调用原本的 chrome api 并返回一个 Promise
48-
* @param {Boolean} [returnArray] - 当函数的第一个值是 true 时,则 Promise 会返回一个数组,包含 callback 的所有参数
49-
* @param {String} fnPath - 原本的 chrome api 的路径,相对于 chrome,如 storage.local.get
50-
* @returns {Promise}
51-
*/
52-
return function (/* returnArray , fnPath , ...args */) {
53-
// inline copy arguments,
54-
// see https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
55-
var length = arguments.length
56-
var argumentsArray = []
41+
return function (...args) {
42+
let returnArray = args.shift()
43+
let fnPath
5744

58-
for (var i = 0; i < length; i += 1) {
59-
argumentsArray[i] = arguments[i]
60-
}
61-
62-
var returnArray = argumentsArray.shift()
63-
var fnPath
45+
if (typeof returnArray === 'boolean') {
46+
fnPath = args.shift()
47+
} else {
48+
fnPath = returnArray
49+
returnArray = false
50+
}
6451

65-
if (typeof returnArray === 'boolean') {
66-
fnPath = argumentsArray.shift()
67-
} else {
68-
fnPath = returnArray
69-
returnArray = false
70-
}
52+
// Step 1: find the function which need to be call
53+
const stack = pathStack(fnPath, baseObj)
7154

72-
// Step 1: find the function which need to be call
73-
var stack = pathStack(fnPath, baseObj)
55+
return new Promise((resolve, reject) => {
56+
// Step 2: inject callback
57+
args.push((...results) => {
58+
const { lastError } = runtime
59+
if (lastError) {
60+
reject(lastError)
61+
return
62+
}
7463

75-
var args = argumentsArray
76-
return new Promise(function (resolve, reject) {
77-
// Step 2: inject callback
78-
args.push(function () {
79-
var lastError = runtime.lastError
80-
if (lastError) {
81-
reject(lastError)
82-
return
83-
}
64+
if (returnArray) {
65+
resolve(results)
66+
} else {
67+
resolve(results[0])
68+
}
69+
})
8470

85-
if (returnArray) {
86-
var length = arguments.length
87-
var argumentsArray = []
71+
// Step 3: call function with it's original "this"
72+
stack.pop().apply(stack.pop(), args)
73+
})
74+
}
75+
}
8876

89-
for (var i = 0; i < length; i += 1) {
90-
argumentsArray[i] = arguments[i]
91-
}
77+
const call = scope(chrome)
9278

93-
resolve(argumentsArray)
94-
} else {
95-
resolve(arguments[0])
96-
}
97-
})
79+
export { scope, call }
9880

99-
// Step 3: call function with it's original "this"
100-
stack.pop().apply(stack.pop(), args)
101-
})
102-
}
103-
}
10481

105-
var defaultCp = scope(chrome)
106-
defaultCp.scope = scope
107-
return defaultCp
108-
})

karma.conf.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,17 @@ module.exports = function (config) {
99
'test/test.js'
1010
],
1111
preprocessors: {
12-
'chrome-call.js': ['coverage']
12+
'chrome-call.js': ['rollup', 'coverage']
1313
},
1414
reporters: ['progress', 'coverage'],
15+
rollupPreprocessor: {
16+
plugins: [
17+
require('rollup-plugin-buble')(),
18+
],
19+
format: 'iife',
20+
moduleName: 'chromeCall',
21+
sourceMap: 'inline',
22+
},
1523
coverageReporter: {
1624
dir: 'coverage',
1725
reporters: [

0 commit comments

Comments
 (0)