Skip to content

feat: Initial commit #1

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 13 commits into from
Oct 18, 2018
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
13 changes: 13 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# editorconfig.org
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules/
*.log
yarn.lock
package-lock.json
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
lts/*
15 changes: 15 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
language: node_js
cache:
directories:
- node_modules
notifications:
email: false
before_script:
- npm prune
script:
- npm test
after_success:
- npm run travis-deploy-once "npm run semantic-release"
branches:
except:
- /^v\d+\.\d+\.\d+$/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 SEEK

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
66 changes: 65 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,67 @@
# css-modules-typescript-loader

Webpack loader to create type declarations for css modules
[Webpack](https://webpack.js.org/) loader to create [TypeScript](https://www.typescriptlang.org/) declarations for [CSS Modules](https://github.com/css-modules/css-modules).

Emits TypeScript declaration files matching your CSS Modules in the same location as your source files, e.g. `src/Component.css` will generate `src/Component.css.d.ts`.

## Why?

There are currently a lot of [solutions to this problem](https://www.npmjs.com/search?q=css%20modules%20typescript%20loader). However, this package differs in the following ways:

- Encourages generated TypeScript declarations to be checked into source control, which allows `webpack` and `tsc` commands to be run in parallel in CI.

- Ensures committed TypeScript declarations are in sync with the code that generated them via the [`verify` mode](#verify-mode).

- Doesn't silently ignore invalid TypeScript identifiers. If a class name is not valid TypeScript (e.g. `.foo-bar`, instead of `.fooBar`), `tsc` should report an error.

## Usage

Place `css-modules-typescript-loader` directly after `css-loader` in your webpack config.

```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
'css-modules-typescript-loader',
{
loader: 'css-loader',
options: {
modules: true
}
}
]
}
]
}
};
```

### Verify Mode

Since the TypeScript declarations are generated by `webpack`, they may potentially be out of date by the time you run `tsc`. To ensure your types are up to date, you can run the loader in `verify` mode, which is particularly useful in CI.

For example:

```js
{
loader: 'css-modules-typescript-loader',
options: {
mode: process.env.CI ? 'verify' : 'emit'
}
}
```

Instead of emitting new TypeScript declarations, this will throw an error if a generated declaration doesn't match the committed one. This allows `tsc` and `webpack` to run in parallel in CI, if desired.

This workflow is similar to using the [Prettier](https://github.com/prettier/prettier) [`--list-different` option](https://prettier.io/docs/en/cli.html#list-different).

## With Thanks

This package borrows heavily from [typings-for-css-modules-loader](https://github.com/Jimdo/typings-for-css-modules-loader).

## License

MIT.
92 changes: 92 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
const fs = require('fs');
const path = require('path');
const loaderUtils = require('loader-utils');

const bannerMessage =
'// This file is automatically generated.\n// Please do not change this file!';

const getNoDeclarationFileError = cssModuleInterfaceFilename =>
new Error(
`Generated type declaration does not exist. Run webpack and commit the type declaration for '${cssModuleInterfaceFilename}'`
);

const getTypeMismatchError = cssModuleInterfaceFilename =>
new Error(
`Generated type declaration file is outdated. Run webpack and commit the updated type declaration for '${cssModuleInterfaceFilename}'`
);

const cssModuleToNamedExports = cssModuleKeys => {
return cssModuleKeys
.map(key => `export const ${key}: string;`)
.join('\n')
.concat('\n');
};

const filenameToTypingsFilename = filename => {
const dirName = path.dirname(filename);
const baseName = path.basename(filename);
return path.join(dirName, `${baseName}.d.ts`);
};

const validModes = ['emit', 'verify'];

module.exports = function(content, ...rest) {
const callback = this.async();

const filename = this.resourcePath;
const { mode = 'emit' } = loaderUtils.getOptions(this) || {};
if (!validModes.includes(mode)) {
return callback(new Error(`Invalid mode option: ${mode}`));
}

const cssModuleInterfaceFilename = filenameToTypingsFilename(filename);

const keyRegex = /"([^\\"]+)":/g;
let match;
const cssModuleKeys = [];

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

const cssModuleDefinition = `${bannerMessage}\n${cssModuleToNamedExports(
cssModuleKeys
)}`;

if (mode === 'verify') {
fs.readFile(
cssModuleInterfaceFilename,
{ encoding: 'utf-8' },
(err, fileContents) => {
if (err) {
const error =
err.code === 'ENOENT'
? getNoDeclarationFileError(cssModuleInterfaceFilename)
: err;
return callback(error);
}

if (cssModuleDefinition !== fileContents) {
return callback(getTypeMismatchError(cssModuleInterfaceFilename));
}

return callback(null, content, ...rest);
}
);
} else {
fs.writeFile(
cssModuleInterfaceFilename,
cssModuleDefinition,
{ encoding: 'utf-8' },
err => {
if (err) {
return callback(err);
} else {
return callback(null, content, ...rest);
}
}
);
}
};
51 changes: 51 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"name": "css-modules-typescript-loader",
"version": "0.0.0-development",
"description": "Webpack loader to create TypeScript declarations for CSS Modules",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/seek-oss/css-modules-typescript-loader.git"
},
"author": "SEEK",
"license": "MIT",
"bugs": {
"url": "https://github.com/seek-oss/css-modules-typescript-loader/issues"
},
"scripts": {
"commit": "git-cz",
"travis-deploy-once": "travis-deploy-once",
"semantic-release": "semantic-release",
"test": "jest"
},
"jest": {
"testEnvironment": "node"
},
"husky": {
"hooks": {
"commit-msg": "commitlint --edit --extends seek"
}
},
"homepage": "https://github.com/seek-oss/css-modules-typescript-loader#readme",
"devDependencies": {
"@commitlint/cli": "^7.2.1",
"commitizen": "^3.0.2",
"commitlint-config-seek": "^1.0.0",
"css-loader": "^1.0.0",
"cz-conventional-changelog": "^2.1.0",
"husky": "^1.1.2",
"jest": "^23.6.0",
"memory-fs": "^0.4.1",
"semantic-release": "^15.9.17",
"travis-deploy-once": "^5.0.9",
"webpack": "^4.21.0"
},
"release": {
"success": false
},
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
}
}
48 changes: 48 additions & 0 deletions test/compiler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
const path = require('path');
const webpack = require('webpack');
const memoryfs = require('memory-fs');

module.exports = (entry, options = {}) => {
const compiler = webpack({
context: path.dirname(entry),
entry,
output: {
path: path.dirname(entry),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: require.resolve('../index.js'),
options
},
{
loader: 'css-loader',
options: {
modules: true
}
}
]
}
]
}
});

compiler.outputFileSystem = new memoryfs();

return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err || stats.hasErrors()) {
reject({
failed: true,
errors: err || stats.toJson().errors
});
}

resolve(stats);
});
});
};
1 change: 1 addition & 0 deletions test/emit-declaration/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
index.css.d.ts
10 changes: 10 additions & 0 deletions test/emit-declaration/__snapshots__/emit-declaration.test.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Can emit valid declaration 1`] = `
"// This file is automatically generated.
// Please do not change this file!
export const validClass: string;
export const someClass: string;
export const otherClass: string;
"
`;
13 changes: 13 additions & 0 deletions test/emit-declaration/emit-declaration.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const fs = require('fs');
const compiler = require('../compiler.js');

test('Can emit valid declaration', async () => {
await compiler(require.resolve('./index.js'));

const declaration = fs.readFileSync(
require.resolve('./index.css.d.ts'),
'utf-8'
);

expect(declaration).toMatchSnapshot();
});
11 changes: 11 additions & 0 deletions test/emit-declaration/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.validClass {
position: relative;
}

.someClass {
position: relative;
}

.otherClass {
display: block;
}
1 change: 1 addition & 0 deletions test/emit-declaration/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import styles from './index.css';
7 changes: 7 additions & 0 deletions test/verify-invalid-declaration/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.someClass {
position: relative;
}

.otherClass {
display: block;
}
4 changes: 4 additions & 0 deletions test/verify-invalid-declaration/index.css.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// This file is automatically generated.
// Please do not change this file!
export const someClass: string;
export const differentClass: string;
1 change: 1 addition & 0 deletions test/verify-invalid-declaration/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import styles from './index.css';
11 changes: 11 additions & 0 deletions test/verify-invalid-declaration/verify-invalid-declaration.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const compiler = require('../compiler.js');

test('Can error on invalid declaration', async () => {
await expect(
compiler(require.resolve('./index.js'), {
mode: 'verify'
})
).rejects.toMatchObject({
failed: true
});
});
7 changes: 7 additions & 0 deletions test/verify-missing-declaration/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.someClass {
position: relative;
}

.otherClass {
display: block;
}
Loading