Skip to content

Commit

Permalink
support webpack 5
Browse files Browse the repository at this point in the history
  • Loading branch information
bahtou committed Nov 28, 2020
1 parent c331674 commit 398a1e5
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 36 deletions.
74 changes: 40 additions & 34 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,53 +2,54 @@
const {
filenameToPascalCase,
filenameToTypingsFilename,
getCssModuleKeys,
getCssModuleLocalKeys,
getCssModuleNamedExportsKeys,
generateGenericExportInterface,
} = require("./utils");
const persist = require("./persist");
const verify = require("./verify");
const { getOptions } = require("loader-utils");
const validateOptions = require("schema-utils");
} = require('./utils');
const persist = require('./persist');
const verify = require('./verify');
const { getOptions } = require('loader-utils');
const validateOptions = require('schema-utils');

const schema = {
type: "object",
type: 'object',
properties: {
eol: {
description:
"Newline character to be used in generated d.ts files. Uses OS default. This option is overridden by the formatter option.",
type: "string",
'Newline character to be used in generated d.ts files. Uses OS default. This option is overridden by the formatter option.',
type: 'string',
},
banner: {
description: "To add a 'banner' prefix to each generated `*.d.ts` file",
type: "string",
description: 'To add a \'banner\' prefix to each generated `*.d.ts` file',
type: 'string',
},
formatter: {
description:
"Possible options: none and prettier (requires prettier package installed). Defaults to prettier if `prettier` module can be resolved",
enum: ["prettier", "none"],
'Possible options: none and prettier (requires prettier package installed). Defaults to prettier if `prettier` module can be resolved',
enum: ['prettier', 'none'],
},
disableLocalsExport: {
description: "Disable the use of locals export. Defaults to `false`",
type: "boolean",
description: 'isable the use of locals export. Defaults to `false`',
type: 'boolean',
},
verifyOnly: {
description:
"Validate generated `*.d.ts` files and fail if an update is needed (useful in CI). Defaults to `false`",
type: "boolean",
'Validate generated `*.d.ts` files and fail if an update is needed (useful in CI). Defaults to `false`',
type: 'boolean',
},
prettierConfigFile: {
description:
"Path to prettier config file",
type: "string",
'Path to prettier config file',
type: 'string',
}
},
additionalProperties: false,
};

/** @type {any} */
const configuration = {
name: "typings-for-css-modules-loader",
baseDataPath: "options",
name: 'typings-for-css-modules-loader',
baseDataPath: 'options',
};

/** @type {((this: import('webpack').loader.LoaderContext, ...args: any[]) => void) & {pitch?: import('webpack').loader.Loader['pitch']}} */
Expand All @@ -63,11 +64,16 @@ module.exports = function (content, ...args) {

// let's only check `exports.locals` for keys to avoid getting keys from the sourcemap when it's enabled
// if we cannot find locals, then the module only contains global styles
const indexOfLocals = content.indexOf(".locals");
const cssModuleKeys =
indexOfLocals === -1
? []
: getCssModuleKeys(content.substring(indexOfLocals));
const indexOfLocals = content.indexOf('.locals');
const indexOfNamedExports = content.indexOf('export const');

let cssModuleKeys;
if (indexOfLocals === -1 && indexOfNamedExports === -1)
cssModuleKeys = [];
if (indexOfNamedExports === -1)
cssModuleKeys = getCssModuleLocalKeys(content.substring(indexOfLocals))
if (indexOfLocals === -1)
cssModuleKeys = getCssModuleNamedExportsKeys(content.substring(indexOfLocals))

/** @type {any} */
const callback = this.async();
Expand Down Expand Up @@ -112,19 +118,19 @@ module.exports = function (content, ...args) {
async function applyFormattingAndOptions(cssModuleDefinition, options) {
if (options.banner) {
// Prefix banner to CSS module
cssModuleDefinition = options.banner + "\n" + cssModuleDefinition;
cssModuleDefinition = options.banner + '\n' + cssModuleDefinition;
}

if (
options.formatter === "prettier" ||
options.formatter === 'prettier' ||
(!options.formatter && canUsePrettier())
) {
cssModuleDefinition = await applyPrettier(cssModuleDefinition, options);
} else {
// at very least let's ensure we're using OS eol if it's not provided
cssModuleDefinition = cssModuleDefinition.replace(
/\r?\n/g,
options.eol || require("os").EOL
options.eol || require('os').EOL
);
}

Expand All @@ -137,16 +143,16 @@ async function applyFormattingAndOptions(cssModuleDefinition, options) {
* @returns {Promise<string>}
*/
async function applyPrettier(input, options) {
const prettier = require("prettier");
const prettier = require('prettier');

const configPath = options.prettierConfigFile ? options.prettierConfigFile : "./";
const configPath = options.prettierConfigFile ? options.prettierConfigFile : './';
const config = await prettier.resolveConfig(configPath, {
editorconfig: true,
});

return prettier.format(
input,
Object.assign({}, config, { parser: "typescript" })
Object.assign({}, config, { parser: 'typescript' })
);
}

Expand All @@ -155,9 +161,9 @@ let isPrettierInstalled;
* @returns {boolean}
*/
function canUsePrettier() {
if (typeof isPrettierInstalled !== "boolean") {
if (typeof isPrettierInstalled !== 'boolean') {
try {
require.resolve("prettier");
require.resolve('prettier');
isPrettierInstalled = true;
} catch (_) {
isPrettierInstalled = false;
Expand Down
22 changes: 20 additions & 2 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const camelCase = require("camelcase");
* @param {string} content
* @returns {string[]}
*/
const getCssModuleKeys = (content) => {
const getCssModuleLocalKeys = (content) => {
const keyRegex = /"([\w-]+)":/g;
let match;
const cssModuleKeys = [];
Expand All @@ -19,6 +19,23 @@ const getCssModuleKeys = (content) => {
return cssModuleKeys;
};

/**
* @param {string} content
* @returns {string[]}
*/
const getCssModuleNamedExportsKeys = (content) => {
const keyRegex = /export const ([\w-]+) =/g;
let match;
const cssModuleKeys = [];

while ((match = keyRegex.exec(content))) {
if (cssModuleKeys.indexOf(match[1]) < 0) {
cssModuleKeys.push(match[1]);
}
}
return cssModuleKeys;
};

/**
* @param {string} filename
*/
Expand Down Expand Up @@ -79,7 +96,8 @@ export = ${moduleName};`;
};

module.exports = {
getCssModuleKeys,
getCssModuleLocalKeys,
getCssModuleNamedExportsKeys,
filenameToPascalCase,
filenameToTypingsFilename,
generateGenericExportInterface,
Expand Down

0 comments on commit 398a1e5

Please sign in to comment.