Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add type definitions #88

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12,576 changes: 39 additions & 12,537 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@
"url": "https://opencollective.com/webpack"
},
"main": "dist/cjs.js",
"types": "types/index.d.ts",
"engines": {
"node": ">= 12.13.0"
},
"scripts": {
"start": "npm run build -- -w",
"build:types": "tsc --declaration --emitDeclarationOnly --outDir types && prettier \"types/**/*.ts\" --write",
"clean": "del-cli dist",
"prebuild": "npm run clean",
"build": "cross-env NODE_ENV=production babel src -d dist --copy-files",
Expand All @@ -34,7 +36,8 @@
"release": "standard-version"
},
"files": [
"dist"
"dist",
"types"
],
"peerDependencies": {
"webpack": "^5.0.0"
Expand Down Expand Up @@ -64,6 +67,7 @@
"npm-run-all": "^4.1.5",
"prettier": "^2.6.2",
"standard-version": "^9.3.1",
"typescript": "^4.6.4",
"webpack": "^5.72.0"
},
"keywords": [
Expand Down
24 changes: 22 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,26 @@ import { getExports, renderExports } from "./utils";

const FOOTER = "/*** EXPORTS FROM exports-loader ***/\n";

/** @typedef {import("source-map").RawSourceMap} RawSourceMap */
/** @typedef {import("schema-utils/declarations/validate").Schema} Schema */

/**
* @template T
* @typedef {Object} LoaderOptions<T>Allows to choose how errors are displayed.
* @property {"commonjs" | "module"} [type]
* @property {string| object | string[] | object[]} exports
*/

/**
* The exports loader allows to setup exports
* @template T
* @this {import("webpack").LoaderContext<LoaderOptions<T>>}
* @param {string} content
* @param { RawSourceMap } sourceMap
*/

export default function loader(content, sourceMap) {
const options = this.getOptions(schema);
const options = this.getOptions(/** @type {Schema} */ (schema));
const type = options.type || "module";
const callback = this.async();

Expand All @@ -19,7 +37,7 @@ export default function loader(content, sourceMap) {
try {
exports = getExports(type, options.exports);
} catch (error) {
callback(error);
callback(/** @type {Error | null | undefined} */ (error));

return;
}
Expand All @@ -36,10 +54,12 @@ export default function loader(content, sourceMap) {

const result = node.toStringWithSourceMap({ file: this.resourcePath });

// @ts-ignore map only has toString() method in types
callback(null, result.code, result.map.toJSON());

return;
}

// @ts-ignore sourceMap in the webpack doesn't have the type RawSourceMap
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should avoid ignore

Copy link
Author

@harish-sethuraman harish-sethuraman May 11, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the callback(null, ${content}\n${FOOTER}${exportsCode}, sourceMap); takes type def SourceMap that is not exported from webpack. Should we export that and consume it here?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Weird, it is interface with the same methods...

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is in webpack

declare interface SourceMap {
	version: number;
	sources: string[];
	mappings: string;
	file?: string;
	sourceRoot?: string;
	sourcesContent?: string[];
	names?: string[];
}

This is in source-map

export interface RawSourceMap extends StartOfSourceMap {
    version: string;
    sources: string[];
    names: string[];
    sourcesContent?: string[];
    mappings: string;
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should investigate it, maybe add better types, because ignore is not good idea for types, looks like problem in version, we can improve it

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

which version are you mentioning? webpack? It is in its latest version. I hope the source-map is in latest version as well?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if we export the SourceMap from webpack and consume it? Is it not recommended

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think webpack have own types for source maps due to this we have problems with types

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bump

callback(null, `${content}\n${FOOTER}${exportsCode}`, sourceMap);
}
75 changes: 72 additions & 3 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,47 @@
/** @typedef {import("source-map").RawSourceMap} RawSourceMap */

/**
* @template T
* @typedef {Object} LoaderOptions<T>
* @property {string} [type]
* @property {string| object | string[] | object[]} [exports]
*/

/**
* The exports loader allows to setup exports
* @template T
* @typedef {import("webpack").LoaderContext<LoaderOptions<T>>} LoaderOption
* @param {string} content
* @param { RawSourceMap } sourceMap
*/

/**
* @typedef {Object} Identifier
* @property {string} type
* @property {string} [value]
*/

/**
* @typedef {Object} Export
* @property {string} syntax
* @property {string} [name]
* @property {string} [alias]
*/

/**
*
* @param {string | object | string[] | Object[]} item
* @returns
*/
function forError(item) {
return typeof item === "string"
? item
: `\n${JSON.stringify(item, null, " ")}\n`;
}

/**
* @param {string} command
*/
function splitCommand(command) {
const result = command
.split("|")
Expand All @@ -21,8 +59,13 @@ function splitCommand(command) {
return result;
}

/**
*
* @param {string} type
* @param {string | object | string[] | Object[] } item
*/
function resolveExports(type, item) {
let result;
let /** @type {Export} */ result;

if (typeof item === "string") {
const noWhitespaceItem = item.trim();
Expand Down Expand Up @@ -97,8 +140,12 @@ function resolveExports(type, item) {
return result;
}

/**
*
* @param {Array<Export>} array
*/
function getIdentifiers(array) {
return array.reduce((accumulator, item) => {
return array.reduce((/** @type {Array<Identifier>} */ accumulator, item) => {
if (typeof item.alias !== "undefined") {
accumulator.push({ type: "alias", value: item.alias });

Expand All @@ -111,6 +158,12 @@ function getIdentifiers(array) {
}, []);
}

/**
*
* @param {string} type
* @param {string| object | string[] | object[]} exports
* @returns
*/
function getExports(type, exports) {
let result;
const exportItems =
Expand Down Expand Up @@ -142,7 +195,10 @@ function getExports(type, exports) {
if (duplicates.length > 0) {
throw new Error(
`Duplicate ${duplicates
.map((identifier) => `"${identifier.value}" (as "${identifier.type}")`)
.map(
(/** @type {Identifier} */ identifier) =>
`"${identifier.value}" (as "${identifier.type}")`
)
.join(", ")} identifiers found in "\n${JSON.stringify(
exports,
null,
Expand All @@ -154,6 +210,12 @@ function getExports(type, exports) {
return result;
}

/**
*
* @param {Identifier[]} array
* @param {"value"} key
* @returns
*/
function duplicateBy(array, key) {
return array.filter(
(a, aIndex) =>
Expand All @@ -162,6 +224,13 @@ function duplicateBy(array, key) {
);
}

/**
* @template T
* @param {LoaderOption<T>} loaderContext
* @param {"commonjs"|"module"} type
* @param {Array<Export>} exports
* @returns
*/
function renderExports(loaderContext, type, exports) {
let code = "";

Expand Down
14 changes: 14 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "esnext",
"moduleResolution": "node",
"allowJs": true,
"checkJs": true,
"strict": true,
"types": ["node"],
"resolveJsonModule": true,
"newLine": "LF",
"allowSyntheticDefaultImports": true
},
"include": ["./src/**/*"]
}
3 changes: 3 additions & 0 deletions types/cjs.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
declare const _exports: typeof loader.default;
export = _exports;
import loader = require("./index");
29 changes: 29 additions & 0 deletions types/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/** @typedef {import("source-map").RawSourceMap} RawSourceMap */
/** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
/**
* @template T
* @typedef {Object} LoaderOptions<T>Allows to choose how errors are displayed.
* @property {"commonjs" | "module"} [type]
* @property {string| object | string[] | object[]} exports
*/
/**
* The exports loader allows to setup exports
* @template T
* @this {import("webpack").LoaderContext<LoaderOptions<T>>}
* @param {string} content
* @param { RawSourceMap } sourceMap
*/
export default function loader<T>(
this: import("webpack").LoaderContext<LoaderOptions<T>>,
content: string,
sourceMap: RawSourceMap
): void;
export type RawSourceMap = import("source-map").RawSourceMap;
export type Schema = import("schema-utils/declarations/validate").Schema;
/**
* <T>Allows to choose how errors are displayed.
*/
export type LoaderOptions<T> = {
type?: "module" | "commonjs" | undefined;
exports: string | object | string[] | object[];
};
43 changes: 43 additions & 0 deletions types/utils.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
export type RawSourceMap = import("source-map").RawSourceMap;
/**
* <T>
*/
export type LoaderOptions<T> = {
type?: string | undefined;
exports?: string | object | string[] | object[] | undefined;
};
/**
* The exports loader allows to setup exports
*/
export type LoaderOption<T> = import("webpack").LoaderContext<LoaderOptions<T>>;
export type Identifier = {
type: string;
value?: string | undefined;
};
export type Export = {
syntax: string;
name?: string | undefined;
alias?: string | undefined;
};
/**
*
* @param {string} type
* @param {string| object | string[] | object[]} exports
* @returns
*/
export function getExports(
type: string,
exports: string | object | string[] | object[]
): Export[];
/**
* @template T
* @param {LoaderOption<T>} loaderContext
* @param {"commonjs"|"module"} type
* @param {Array<Export>} exports
* @returns
*/
export function renderExports<T>(
loaderContext: import("webpack").LoaderContext<LoaderOptions<T>>,
type: "commonjs" | "module",
exports: Array<Export>
): string;