Skip to content

Commit

Permalink
feat(TypeScript): Move DeviceDescriptors to TS
Browse files Browse the repository at this point in the history
This commit moves `src/DeviceDescriptors` to be authored in TypeScript.
This file was chosen due to its simplicity so that we can focus on
getting a mixed JS/TS codebase playing nicely before migrating the more
complex files.

The file itself was a bit odd: although the array of devices was
exported via `module.exports` that was never referenced by any
consumers; each device was also exported via `module.exports[name] =
device` and that is how it's consumed. The Puppeteer docs suggest using
it like so:

```js
puppeteer.devices['iPhone 6']
```

So instead of exporting the array and then setting a bunch of properties
on that, we instead define the array and export an object of keys where
each key is a device.

Rather than export an object I'd much rather export a Map, but that
would be a breaking change and I'm keen to avoid those for the time
being.

Note that we have to use special TypeScript specific syntax for the
export that enables it to work in a CommonJS codebase [1] but again I'd
rather this than move to ESM at this time. TypeScript still outputs
CommonJS into `lib/` as you would expect.

[1]: https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require
  • Loading branch information
jackfranklin committed Apr 6, 2020
1 parent efe561e commit 83b7455
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
29 changes: 26 additions & 3 deletions src/DeviceDescriptors.js → src/DeviceDescriptors.ts
Expand Up @@ -14,7 +14,20 @@
* limitations under the License.
*/

module.exports = [
interface Device {
name: string;
userAgent: string;
viewport: {
width: number;
height: number;
deviceScaleFactor: number;
isMobile: boolean;
hasTouch: boolean;
isLandscape: boolean
}
};

const devices: Device[] = [
{
'name': 'Blackberry PlayBook',
'userAgent': 'Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+',
Expand Down Expand Up @@ -868,5 +881,15 @@ module.exports = [
}
}
];
for (const device of module.exports)
module.exports[device.name] = device;

type DevicesMap = {
[name: string]: Device
}

const devicesMap: DevicesMap = {}

for (const device of devices) {
devicesMap[device.name] = device;
}

export = devicesMap;
3 changes: 2 additions & 1 deletion tsconfig.json
Expand Up @@ -3,7 +3,8 @@
"allowJs": true,
"checkJs": true,
"outDir": "./lib",
"target": "ESNext"
"target": "ESNext",
"module": "CommonJS"
},
"include": [
"src"
Expand Down

0 comments on commit 83b7455

Please sign in to comment.