Skip to content

Commit 3095753

Browse files
committed
fix: add typings to package
1 parent 4c91b75 commit 3095753

File tree

4 files changed

+164
-3
lines changed

4 files changed

+164
-3
lines changed

package.json

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
{
22
"name": "fetch-script",
3-
"version": "0.0.4",
3+
"version": "0.0.5",
44
"description": "Async loading of scripts using the Fetch API",
55
"main": "lib/fetch-script.js",
66
"unpkg": "dist/fetch-script.js",
77
"module": "es/fetch-script.js",
8-
"typings": "fetch-script.d.ts",
8+
"typings": "typings/fetch-script.d.ts",
99
"scripts": {
1010
"build:commonjs": "cross-env NODE_ENV=cjs rollup -c -o lib/fetch-script.js",
1111
"build:es": "cross-env BABEL_ENV=es NODE_ENV=es rollup -c -o es/fetch-script.js",
@@ -28,7 +28,8 @@
2828
"dist",
2929
"lib",
3030
"es",
31-
"src"
31+
"src",
32+
"typings"
3233
],
3334
"devDependencies": {
3435
"@babel/core": "^7.6.0",

src/index.ts

+96
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import { head, headCors } from './injectors';
2+
3+
const networkError = 'Network response was not ok.';
4+
5+
function contentLoadedEvent() {
6+
const DOMContentLoadedEvent = document.createEvent('Event');
7+
DOMContentLoadedEvent.initEvent('DOMContentLoaded', true, true);
8+
document.dispatchEvent(DOMContentLoadedEvent);
9+
}
10+
/**
11+
* Fetch Script module.
12+
*/
13+
function fetchInject(scripts, promise) {
14+
if (!scripts) {
15+
return Promise.reject(
16+
new ReferenceError(
17+
"Failed to execute 'fetchInject': 1 argument required but only 0 present.",
18+
),
19+
);
20+
}
21+
if (scripts && !Array.isArray(scripts)) {
22+
return Promise.reject(
23+
new TypeError("Failed to execute 'fetchInject': argument 1 must be of type 'Array'."),
24+
);
25+
}
26+
if (promise && promise.constructor !== Promise) {
27+
return Promise.reject(
28+
new TypeError("Failed to execute 'fetchInject': argument 2 must be of type 'Promise'."),
29+
);
30+
}
31+
32+
const resources = [];
33+
const deferreds = promise ? [].concat(promise) : [];
34+
const thenables = [];
35+
36+
scripts.forEach((input) => {
37+
let options;
38+
let url = input;
39+
if (typeof input === 'object') {
40+
({ options, url } = input);
41+
}
42+
if (options && options.mode === 'no-cors' && options.method === 'GET') {
43+
// can not use fetch, inject the script into the head
44+
deferreds.push(
45+
new Promise((resolve, reject) => {
46+
headCors(
47+
window,
48+
document,
49+
'script',
50+
url,
51+
() => {
52+
contentLoadedEvent();
53+
resolve();
54+
},
55+
() => {
56+
reject(new Error(networkError));
57+
},
58+
);
59+
}),
60+
);
61+
} else {
62+
deferreds.push(
63+
window
64+
.fetch(url, options)
65+
.then((res) => {
66+
if (!res.ok) {
67+
throw Error(networkError);
68+
}
69+
return [res.clone().text(), res.blob()];
70+
})
71+
.then((promises) =>
72+
Promise.all(promises).then((resolved) =>
73+
resources.push({ text: resolved[0], blob: resolved[1] }),
74+
),
75+
),
76+
);
77+
}
78+
});
79+
80+
return Promise.all(deferreds).then(() => {
81+
resources.forEach((resource) => {
82+
thenables.push({
83+
then: (resolve) => {
84+
if (resource.blob.type.includes('text/css')) {
85+
head(window, document, 'style', resource, resolve);
86+
} else {
87+
head(window, document, 'script', resource, resolve);
88+
}
89+
},
90+
});
91+
});
92+
return Promise.all(thenables);
93+
});
94+
}
95+
96+
export default fetchInject;

tsconfig.json

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
{
2+
"compilerOptions": {
3+
/* Basic Options */
4+
// "incremental": true, /* Enable incremental compilation */
5+
"target": "esnext", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
6+
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
7+
// "lib": [], /* Specify library files to be included in the compilation. */
8+
// "allowJs": true, /* Allow javascript files to be compiled. */
9+
// "checkJs": true, /* Report errors in .js files. */
10+
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
11+
"declaration": true, /* Generates corresponding '.d.ts' file. */
12+
"declarationDir": "./typings", /* Output declarations to a sepcific directory */
13+
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
14+
"sourceMap": true, /* Generates corresponding '.map' file. */
15+
// "outFile": "./", /* Concatenate and emit output to single file. */
16+
"outDir": "lib", /* Redirect output structure to the directory. */
17+
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
18+
// "composite": true, /* Enable project compilation */
19+
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
20+
// "removeComments": true, /* Do not emit comments to output. */
21+
// "noEmit": true, /* Do not emit outputs. */
22+
"importHelpers": false, /* Import emit helpers from 'tslib'. */
23+
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
24+
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
25+
26+
/* Strict Type-Checking Options */
27+
"strict": true, /* Enable all strict type-checking options. */
28+
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
29+
// "strictNullChecks": true, /* Enable strict null checks. */
30+
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
31+
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
32+
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
33+
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
34+
"alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
35+
36+
/* Additional Checks */
37+
"noUnusedLocals": true, /* Report errors on unused locals. */
38+
"noUnusedParameters": true, /* Report errors on unused parameters. */
39+
"noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
40+
"noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
41+
42+
/* Module Resolution Options */
43+
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
44+
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
45+
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
46+
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
47+
// "typeRoots": [], /* List of folders to include type definitions from. */
48+
// "types": [], /* Type declaration files to be included in compilation. */
49+
"allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
50+
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
51+
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
52+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
53+
54+
/* Source Map Options */
55+
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
56+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
57+
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
58+
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
59+
60+
/* Experimental Options */
61+
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
62+
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
63+
}
64+
}
File renamed without changes.

0 commit comments

Comments
 (0)