Skip to content

Add css-loader 4 support #36

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

Merged
merged 3 commits into from
Aug 19, 2020
Merged
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
11 changes: 11 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
language: node_js

node_js:
- "10"

branches:
only:
- master

jobs:
include:
- install: npm ci
- install: npm install --no-shrinkwrap

before_script:
- npm ls css-loader
- npm ls typescript
63 changes: 62 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
},
"devDependencies": {
"@types/jest": "^24.0.23",
"css-loader": "^3.1.0",
"css-loader": "*",
"css-loader3": "npm:css-loader@^3.1.0",
"eslint": "4.18.2",
"eslint-config-prettier": "^6.0.0",
"jest": "^24.9.0",
Expand Down
38 changes: 20 additions & 18 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const {
filenameToPascalCase,
filenameToTypingsFilename,
getCssModuleKeys,
generateGenericExportInterface
generateGenericExportInterface,
} = require("./utils");
const persist = require("./persist");
const verify = require("./verify");
Expand All @@ -16,39 +16,38 @@ const schema = {
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"
type: "string",
},
banner: {
description: "To add a 'banner' prefix to each generated `*.d.ts` file",
type: "string"
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"]
enum: ["prettier", "none"],
},
disableLocalsExport: {
description:
"Disable the use of locals export. Defaults to `false`",
type: "boolean"
description: "Disable 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"
}
type: "boolean",
},
},
additionalProperties: false
additionalProperties: false,
};

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

/** @type {((this: import('webpack').loader.LoaderContext, ...args: any[]) => void) & {pitch?: import('webpack').loader.Loader['pitch']}} */
module.exports = function(content, ...args) {
module.exports = function (content, ...args) {
const options = getOptions(this) || {};

validateOptions(schema, options, configuration);
Expand All @@ -58,9 +57,12 @@ module.exports = function(content, ...args) {
}

// let's only check `exports.locals` for keys to avoid getting keys from the sourcemap when it's enabled
const cssModuleKeys = getCssModuleKeys(
content.substring(content.indexOf("exports.locals"))
);
// 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));

/** @type {any} */
const callback = this.async();
Expand All @@ -85,14 +87,14 @@ module.exports = function(content, ...args) {
);

applyFormattingAndOptions(cssModuleDefinition, options)
.then(output => {
.then((output) => {
if (options.verifyOnly === true) {
return verify(cssModuleInterfaceFilename, output);
} else {
persist(cssModuleInterfaceFilename, output);
}
})
.catch(err => {
.catch((err) => {
this.emitError(err);
})
.then(successfulCallback);
Expand Down Expand Up @@ -132,7 +134,7 @@ async function applyPrettier(input) {
const prettier = require("prettier");

const config = await prettier.resolveConfig("./", {
editorconfig: true
editorconfig: true,
});

return prettier.format(
Expand Down
20 changes: 13 additions & 7 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 getCssModuleKeys = (content) => {
const keyRegex = /"([\w-]+)":/g;
let match;
const cssModuleKeys = [];
Expand All @@ -22,7 +22,7 @@ const getCssModuleKeys = content => {
/**
* @param {string} filename
*/
const filenameToPascalCase = filename => {
const filenameToPascalCase = (filename) => {
return camelCase(path.basename(filename), { pascalCase: true });
};

Expand All @@ -33,11 +33,11 @@ const filenameToPascalCase = filename => {
const cssModuleToTypescriptInterfaceProperties = (cssModuleKeys, indent) => {
return [...cssModuleKeys]
.sort()
.map(key => `${indent || ""}'${key}': string;`)
.map((key) => `${indent || ""}'${key}': string;`)
.join("\n");
};

const filenameToTypingsFilename = filename => {
const filenameToTypingsFilename = (filename) => {
const dirName = path.dirname(filename);
const baseName = path.basename(filename);
return path.join(dirName, `${baseName}.d.ts`);
Expand All @@ -47,12 +47,18 @@ const filenameToTypingsFilename = filename => {
* @param {string[]} cssModuleKeys
* @param {string} pascalCaseFileName
*/
const generateGenericExportInterface = (cssModuleKeys, pascalCaseFileName, disableLocalsExport) => {
const generateGenericExportInterface = (
cssModuleKeys,
pascalCaseFileName,
disableLocalsExport
) => {
const interfaceName = `I${pascalCaseFileName}`;
const moduleName = `${pascalCaseFileName}Module`;
const namespaceName = `${pascalCaseFileName}Namespace`;

const localsExportType = disableLocalsExport ? `` : ` & {
const localsExportType = disableLocalsExport
? ``
: ` & {
/** WARNING: Only available when \`css-loader\` is used without \`style-loader\` or \`mini-css-extract-plugin\` */
locals: ${namespaceName}.${interfaceName};
}`;
Expand All @@ -76,5 +82,5 @@ module.exports = {
getCssModuleKeys,
filenameToPascalCase,
filenameToTypingsFilename,
generateGenericExportInterface
generateGenericExportInterface,
};
21 changes: 13 additions & 8 deletions src/verify.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @ts-check
const fs = require('fs');
const util = require('util');
const fs = require("fs");
const util = require("util");
const fsStat = util.promisify(fs.stat);
const fsReadFile = util.promisify(fs.readFile);
/**
Expand All @@ -10,18 +10,23 @@ const fsReadFile = util.promisify(fs.readFile);
*/
module.exports = async (filename, content) => {
const fileExists = await fsStat(filename)
.then(() => true).catch(() => false);
.then(() => true)
.catch(() => false);

if (!fileExists) {
throw new Error(`Verification failed: Generated typings for css-module file '${filename}' is not found. ` +
"It typically happens when the generated typings were not committed.");
throw new Error(
`Verification failed: Generated typings for css-module file '${filename}' is not found. ` +
"It typically happens when the generated typings were not committed."
);
}

const existingFileContent = await fsReadFile(filename, 'utf-8');
const existingFileContent = await fsReadFile(filename, "utf-8");

// let's not fail the build if there are whitespace changes only
if (existingFileContent.replace(/\s+/g, "") !== content.replace(/\s+/g, "")) {
throw new Error(`Verification failed: Generated typings for css-modules file '${filename}' is out of date. ` +
"It typically happens when the up-to-date generated typings are not committed.");
throw new Error(
`Verification failed: Generated typings for css-modules file '${filename}' is out of date. ` +
"It typically happens when the up-to-date generated typings are not committed."
);
}
};
Loading