Skip to content

Commit a5e29b7

Browse files
committed
build: set typescript complier to rollup config
1 parent 5adcb97 commit a5e29b7

File tree

9 files changed

+197
-21
lines changed

9 files changed

+197
-21
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
node_modules
22
*.log
3+
.rpt2_cache

dist/better-jsonp.js

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
/*!
2+
* better-jsonp v1.1.0 Copyrights (c) 2018 Bowen (lbwa)
3+
* Released under the MIT License.
4+
*/
5+
(function (global, factory) {
6+
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
7+
typeof define === 'function' && define.amd ? define(factory) :
8+
(global.jsonp = factory());
9+
}(this, (function () { 'use strict';
10+
11+
function noop() {}
12+
function defineEnumerable(target, key, value) {
13+
Reflect.defineProperty(target, key, {
14+
enumerable: false,
15+
writable: true,
16+
value: value
17+
});
18+
}
19+
function euc(value) {
20+
return encodeURIComponent(value);
21+
}
22+
23+
var defaultOptions = {
24+
timeout: 6000,
25+
prefix: 'callback',
26+
callbackParams: 'jsonpCallback',
27+
urlParams: {}
28+
};
29+
var Jsonp = /** @class */function () {
30+
function Jsonp(options) {
31+
this.checkOptions(options);
32+
this.initState(options);
33+
this.encodeURL(options.url);
34+
this.insertToElement(this._request);
35+
}
36+
Jsonp.prototype.checkOptions = function (options) {
37+
if (!options || !options.url) throw new Error('Please check your request url.');
38+
this.options = options;
39+
};
40+
Jsonp.prototype.genJsonpCallback = function (options) {
41+
if (options.jsonpCallback) {
42+
this._jsonpCallback = options.jsonpCallback;
43+
} else {
44+
// prefix for callback name in global env
45+
var prefix = defaultOptions.prefix;
46+
// unique global callback name in global env
47+
this._jsonpCallback = prefix + Date.now();
48+
}
49+
};
50+
Jsonp.prototype.defineGlobalCallback = function () {
51+
var _this = this;
52+
/**
53+
* 1. Once invoked window[this._jsonpCallback], it will clean timer for limiting
54+
* request period and script element which is used to JSONP.
55+
* 2. use arrow function to define `this` object value (Jsonp instance).
56+
*/
57+
return new Promise(function (resolve, reject) {
58+
// handle 404/500 in response
59+
// https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror
60+
_this._insertScript.onerror = function () {
61+
_this.cleanScript();
62+
reject(new Error("Countdown has been clear! JSONP request unsuccessfully due to 404/500"));
63+
};
64+
window[_this._jsonpCallback] = function (data) {
65+
_this.cleanScript();
66+
resolve(data);
67+
};
68+
});
69+
};
70+
Jsonp.prototype.genTimer = function (options) {
71+
var _this = this;
72+
// limit request period
73+
var timeout = options.timeout || defaultOptions.timeout;
74+
// use arrow function to define `this` object value (Jsonp instance).
75+
if (timeout) {
76+
this._timer = window.setTimeout(function () {
77+
window[_this._jsonpCallback] = noop;
78+
_this._timer = 0;
79+
_this.cleanScript();
80+
throw new Error('JSONP request unsuccessfully (eg.timeout or wrong url).');
81+
}, timeout);
82+
}
83+
};
84+
Jsonp.prototype.genScript = function () {
85+
this._target = document.getElementsByTagName('script')[0] || document.body.lastElementChild;
86+
this._insertScript = document.createElement('script');
87+
};
88+
Jsonp.prototype.initState = function (options) {
89+
defineEnumerable(this, '_timer', null);
90+
defineEnumerable(this, '_request', null);
91+
defineEnumerable(this, '_jsonpCallback', null);
92+
defineEnumerable(this, '_insertScript', null);
93+
defineEnumerable(this, '_target', null);
94+
this.genScript();
95+
// set this._jsonpCallback
96+
this.genJsonpCallback(options);
97+
// invoke defineGlobalCallback after setting this._jsonpCallback
98+
defineEnumerable(this, '_globalCallback', this.defineGlobalCallback());
99+
// set timer for limit request time
100+
this.genTimer(options);
101+
};
102+
Jsonp.prototype.encodeURL = function (url) {
103+
// name of query parameter to specify the callback name
104+
// eg. ?callback=...
105+
var callbackParams = this.options.callbackParams || defaultOptions.callbackParams;
106+
var id = euc(this._jsonpCallback);
107+
url += "" + (url.indexOf('?') < 0 ? '?' : '&') + callbackParams + "=" + id;
108+
// add other parameter to url excluding callback parameter
109+
var params = this.options.urlParams || defaultOptions.urlParams;
110+
var keys = Object.keys(params);
111+
keys.forEach(function (key) {
112+
var value = params[key] !== undefined ? params[key] : '';
113+
url += "&" + key + "=" + euc(value);
114+
});
115+
this._request = url;
116+
};
117+
// activate JSONP
118+
Jsonp.prototype.insertToElement = function (url) {
119+
this._insertScript.src = url;
120+
this._target.parentNode.insertBefore(this._insertScript, this._target);
121+
};
122+
Jsonp.prototype.cleanScript = function () {
123+
if (this._insertScript.parentNode) {
124+
this._target.parentNode.removeChild(this._insertScript);
125+
this._insertScript = null;
126+
}
127+
window[this._jsonpCallback] = noop;
128+
if (this._timer) window.clearTimeout(this._timer);
129+
};
130+
return Jsonp;
131+
}();
132+
133+
// facade in facade pattern
134+
// same as axios, zepto
135+
function createInstance(options) {
136+
var jsonp = new Jsonp(options);
137+
// from initState(options)
138+
return jsonp._globalCallback;
139+
}
140+
141+
return createInstance;
142+
143+
})));

dist/better-jsonp.min.js

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
"rollup-plugin-babel": "^3.0.4",
6464
"rollup-plugin-replace": "^2.0.0",
6565
"rollup-plugin-terser": "^1.0.1",
66+
"rollup-plugin-typescript2": "^0.15.0",
6667
"typescript": "^2.9.2"
6768
},
6869
"config": {

samples/client.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import jsonp from './jsonp.js'
2-
31
const $ = document.getElementsByClassName.bind(document)
42
const c = document.createElement.bind(document)
53
const js = JSON.stringify.bind(JSON)
@@ -36,6 +34,7 @@ function logger (data) {
3634
}
3735

3836
function generateInstance (options) {
37+
/* eslint-disable no-undef */
3938
jsonp({
4039
...options,
4140
jsonpCallback: options.jsonpCallback || 'jsonpCallback'

samples/dev-page.html

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ <h1 class="card-header">
4242
</div>
4343
</div>
4444
</div>
45-
<script type="module" src="/jsonp.js"></script>
46-
<script type="module" src="/client.js"></script>
45+
<script src="/client.js"></script>
46+
<script src="/dist/better-jsonp.js"></script>
4747
</body>
4848
</html>

samples/server.js

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,34 +19,24 @@ const server = http.createServer((req, res) => {
1919
log(chalk.yellow(`Request url is ${chalk.green(req.url)}`))
2020

2121
// 以运行 node samples/server.js 的路径为基路径,而不是 server.js 所在路径
22-
const html = fs.readFileSync('samples/test-page.html')
23-
const jsonp = fs.readFileSync('lib/jsonp.js')
22+
const html = fs.readFileSync('samples/dev-page.html')
23+
const jsonp = fs.readFileSync('dist/better-jsonp.js')
2424
const client = fs.readFileSync('samples/client.js')
25-
const core = fs.readFileSync('lib/core/Jsonp.js')
26-
const utils = fs.readFileSync('lib/utils/index.js')
2725
const defaultCallback = `jsonpCallback({data: 'Yep! JSONP request Successful!'})`
2826

2927
switch (true) {
3028
case /^\/$/.test(req.url):
3129
sendData(200, 'text/html', html, res)
3230
break
3331

34-
case /\/jsonp/.test(req.url):
32+
case /better-jsonp/.test(req.url):
3533
sendData(200, 'application/javascript', jsonp, res)
3634
break
3735

3836
case /\/client/.test(req.url):
3937
sendData(200, 'application/javascript', client, res)
4038
break
4139

42-
case /\/core/.test(req.url):
43-
sendData(200, 'application/javascript', core, res)
44-
break
45-
46-
case /\/utils/.test(req.url):
47-
sendData(200, 'application/javascript', utils, res)
48-
break
49-
5040
case /\/normal/.test(req.url):
5141
sendData(200, 'application/javascript', defaultCallback, res)
5242
break

scripts/rollup.config.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@ const version = process.env.VERSION || require('../package.json').version
55
const babel = require('rollup-plugin-babel')
66
const replace = require('rollup-plugin-replace')
77
const { terser } = require('rollup-plugin-terser')
8+
const typescript = require('rollup-plugin-typescript2')
89

9-
console.log('Package version :', chalk.red(version))
10+
console.log(chalk.red(`Package version :${version}`))
1011

1112
const banner =
1213
'/*!\n' +
@@ -19,7 +20,7 @@ const resolve = p => path.resolve(__dirname, '../', p)
1920
const builds = {
2021
// be used to link with <script>
2122
'development': {
22-
entry: resolve('lib/jsonp.js'),
23+
entry: resolve('lib/jsonp.ts'),
2324
dest: resolve('dist/better-jsonp.js'),
2425
format: 'umd',
2526
env: 'development',
@@ -28,7 +29,7 @@ const builds = {
2829
},
2930
// be used to link with <script>
3031
'production': {
31-
entry: resolve('lib/jsonp.js'),
32+
entry: resolve('lib/jsonp.ts'),
3233
dest: resolve('dist/better-jsonp.min.js'),
3334
format: 'umd',
3435
env: 'production',
@@ -61,6 +62,11 @@ function genConfig (name) {
6162
// utils: resolve('lib/utils') // url alias, eg. utils -> ../utils
6263
// }),
6364

65+
// keep babel plugin behind typescript plugin
66+
typescript({
67+
tsconfig: 'tsconfig.json'
68+
}),
69+
6470
// convert to lower ES version
6571
babel({
6672
exclude: 'node_modules/**'

yarn.lock

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1438,6 +1438,14 @@ fs-extra@^1.0.0:
14381438
jsonfile "^2.1.0"
14391439
klaw "^1.0.0"
14401440

1441+
fs-extra@^5.0.0:
1442+
version "5.0.0"
1443+
resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-5.0.0.tgz#414d0110cdd06705734d055652c5411260c31abd"
1444+
dependencies:
1445+
graceful-fs "^4.1.2"
1446+
jsonfile "^4.0.0"
1447+
universalify "^0.1.0"
1448+
14411449
fs.realpath@^1.0.0:
14421450
version "1.0.0"
14431451
resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"
@@ -1901,6 +1909,12 @@ jsonfile@^2.1.0:
19011909
optionalDependencies:
19021910
graceful-fs "^4.1.6"
19031911

1912+
jsonfile@^4.0.0:
1913+
version "4.0.0"
1914+
resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-4.0.0.tgz#8771aae0799b64076b76640fca058f9c10e33ecb"
1915+
optionalDependencies:
1916+
graceful-fs "^4.1.6"
1917+
19041918
jsonparse@^1.2.0:
19051919
version "1.3.1"
19061920
resolved "https://registry.yarnpkg.com/jsonparse/-/jsonparse-1.3.1.tgz#3f4dae4a91fac315f71062f8521cc239f1366280"
@@ -2568,7 +2582,7 @@ resolve-from@^1.0.0:
25682582
version "1.0.1"
25692583
resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-1.0.1.tgz#26cbfe935d1aeeeabb29bc3fe5aeb01e93d44226"
25702584

2571-
resolve@^1.1.6, resolve@^1.3.3, resolve@^1.5.0, resolve@^1.6.0:
2585+
resolve@^1.1.6, resolve@^1.3.3, resolve@^1.5.0, resolve@^1.6.0, resolve@^1.7.1:
25722586
version "1.8.1"
25732587
resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.8.1.tgz#82f1ec19a423ac1fbd080b0bab06ba36e84a7a26"
25742588
dependencies:
@@ -2625,6 +2639,15 @@ rollup-plugin-terser@^1.0.1:
26252639
"@babel/code-frame" "^7.0.0-beta.47"
26262640
terser "^3.7.5"
26272641

2642+
rollup-plugin-typescript2@^0.15.0:
2643+
version "0.15.0"
2644+
resolved "https://registry.yarnpkg.com/rollup-plugin-typescript2/-/rollup-plugin-typescript2-0.15.0.tgz#33cf4ec8528f6fa5686cf1246f047acec4801d3a"
2645+
dependencies:
2646+
fs-extra "^5.0.0"
2647+
resolve "^1.7.1"
2648+
rollup-pluginutils "^2.0.1"
2649+
tslib "1.9.2"
2650+
26282651
rollup-pluginutils@^1.5.0:
26292652
version "1.5.2"
26302653
resolved "http://registry.npm.taobao.org/rollup-pluginutils/download/rollup-pluginutils-1.5.2.tgz#1e156e778f94b7255bfa1b3d0178be8f5c552408"
@@ -2918,6 +2941,10 @@ trim-right@^1.0.1:
29182941
version "1.0.1"
29192942
resolved "http://registry.npm.taobao.org/trim-right/download/trim-right-1.0.1.tgz#cb2e1203067e0c8de1f614094b9fe45704ea6003"
29202943

2944+
tslib@1.9.2:
2945+
version "1.9.2"
2946+
resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.9.2.tgz#8be0cc9a1f6dc7727c38deb16c2ebd1a2892988e"
2947+
29212948
type-check@~0.3.2:
29222949
version "0.3.2"
29232950
resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72"
@@ -2945,6 +2972,10 @@ uglify-to-browserify@~1.0.0:
29452972
version "1.0.2"
29462973
resolved "https://registry.yarnpkg.com/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz#6e0924d6bda6b5afe349e39a6d632850a0f882b7"
29472974

2975+
universalify@^0.1.0:
2976+
version "0.1.2"
2977+
resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66"
2978+
29482979
util-deprecate@~1.0.1:
29492980
version "1.0.2"
29502981
resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"

0 commit comments

Comments
 (0)