├── .github ├── dependabot.yml └── workflows │ ├── node.js.yml │ └── stale.yml ├── .gitignore ├── .npmignore ├── .prettierrc ├── CHANGELOG.md ├── LICENSE ├── README.md ├── jest.config.js ├── package-lock.json ├── package.json ├── src └── index.ts ├── test ├── cases │ ├── basic │ │ ├── expected │ │ │ └── style.css.d.ts │ │ ├── index.js │ │ ├── style.css │ │ └── webpack.config.ts │ ├── camelcase │ │ ├── expected │ │ │ └── style.css.d.ts │ │ ├── index.ts │ │ ├── style.css │ │ └── webpack.config.ts │ └── typecheck │ │ ├── expected │ │ └── style.css.d.ts │ │ ├── index.ts │ │ ├── style.css │ │ └── webpack.config.ts └── webpack-integration.test.ts └── tsconfig.json /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "npm" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "daily" 12 | -------------------------------------------------------------------------------- /.github/workflows/node.js.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Node.js CI 5 | 6 | on: [push, pull_request] 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | 13 | strategy: 14 | matrix: 15 | node-version: [10.x, 12.x, 14.x] 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Use Node.js ${{ matrix.node-version }} 20 | uses: actions/setup-node@v1 21 | with: 22 | node-version: ${{ matrix.node-version }} 23 | - run: npm ci 24 | - run: npm run build 25 | - run: npm t 26 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: Mark stale issues and pull requests 2 | 3 | on: 4 | schedule: 5 | - cron: "30 1 * * *" 6 | 7 | jobs: 8 | stale: 9 | 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/stale@v1 14 | with: 15 | repo-token: ${{ secrets.GITHUB_TOKEN }} 16 | stale-issue-message: 'Stale issue message' 17 | stale-pr-message: 'Stale pull request message' 18 | stale-issue-label: 'no-issue-activity' 19 | stale-pr-label: 'no-pr-activity' 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | 33 | # Optional npm cache directory 34 | .npm 35 | 36 | # Optional REPL history 37 | .node_repl_history 38 | 39 | test/fixture/*.js 40 | test/fixture/*.d.ts 41 | dist/ 42 | 43 | # Project specific 44 | test/cases/*/*.css.d.ts 45 | test/build 46 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | test 2 | jest.config.js 3 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 100, 3 | "singleQuote": true, 4 | "trailingComma": "es5", 5 | "bracketSpacing": false 6 | } 7 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. 4 | 5 | ### 0.1.3 (2020-02-04) 6 | 7 | # 0.1.2 8 | 9 | - Update typed-css-modules to 0.6.0. 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2018 Dropbox 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ⚠️ **This project is no longer maintained! We recommend you use a separate tool to build type definitions from the CSS modules.** 2 | 3 | * * * 4 | 5 | # typed-css-modules-webpack-plugin ![Node.js CI](https://github.com/dropbox/typed-css-modules-webpack-plugin/workflows/Node.js%20CI/badge.svg) 6 | 7 | This is a Webpack plugin to generate TypeScript typing declarations for a TypeScript + CSS Modules 8 | project. The plugin generates `.css.d.ts` file co-located with the corresponding `.css` file before 9 | compilation phase so all CSS imports in TypeScript source code type check. 10 | 11 | This plugin is different from [typings-for-css-modules-loader][1] and [dts-css-modules-loader][2] in 12 | that it generates the typings **before** loaders process source files during the compilation. That 13 | means your TypeScript loader will type check the **up-to-date** typing definitions of your CSS modules. 14 | 15 | # Installation 16 | 17 | ``` 18 | yarn add --dev typed-css-modules-webpack-plugin 19 | # Or if you use npm 20 | npm install --save-dev typed-css-modules-webpack-plugin 21 | ``` 22 | 23 | # Usage 24 | 25 | A minimal TypeScript + CSS Modules Webpack configuration would look like this: 26 | 27 | ```javascript 28 | const path = require('path'); 29 | const {TypedCssModulesPlugin} = require('typed-css-modules-webpack-plugin'); 30 | 31 | module.exports = { 32 | entry: './src/index.ts', 33 | output: { 34 | path: path.resolve(__dirname, 'dist'), 35 | filename: 'bundle.js', 36 | }, 37 | module: { 38 | rules: [ 39 | { 40 | test: /\.tsx?$/, 41 | loader: 'ts-loader', 42 | }, 43 | { 44 | test: /\.css$/, 45 | use: [ 46 | 'style-loader', 47 | // Use CSS Modules 48 | { 49 | loader: 'css-loader', 50 | options: { 51 | modules: true, 52 | }, 53 | }, 54 | ], 55 | }, 56 | ], 57 | }, 58 | // Generate typing declarations for all CSS files under `src/` directory. 59 | plugins: [ 60 | new TypedCssModulesPlugin({ 61 | globPattern: 'src/**/*.css', 62 | }), 63 | ], 64 | }; 65 | ``` 66 | 67 | Other than emitting the JS bundle, the build would produce the side-effect of generating `.css.d.ts` 68 | files for all `.css` files in `src/` directory. 69 | 70 | # Options 71 | 72 | The available options for the plugin are: 73 | 74 | ## `globPattern: string` 75 | 76 | This is the glob pattern used to match CSS Modules in the project. The plugin only generates `.d.ts` 77 | for the matching CSS files. See [node-glob](https://github.com/isaacs/node-glob) for the pattern 78 | syntax. 79 | 80 | ## `postCssPlugins?: Plugin[] | (defaults: Plugin[]) => Plugin[]` 81 | 82 | This field is optional. If specified, the plugin would use the specified PostCSS plugin to transform 83 | CSS files instead of the default 84 | [`css-modules-loader-core`](https://github.com/css-modules/css-modules-loader-core) plugins. 85 | 86 | If a function is supplied, it will be called with the default plugin list. This is useful if you 87 | chain a `postcss-loader` before `css-loader` for some custom transformations. For example: 88 | 89 | ```javascript 90 | // In CSS rules 91 | [ 92 | // ... 93 | { 94 | loader: 'css-loader', 95 | options: { 96 | modules: true, 97 | importLoaders: 1, 98 | }, 99 | }, 100 | // Some PostCSS transformations applied before css-loader 101 | { 102 | loader: 'postcss-loader', 103 | options: { 104 | plugins: () => [require('postcss-theme')({themePath: './theme'})], 105 | }, 106 | }, 107 | ]; 108 | ``` 109 | 110 | Now to ensure CSS Modules recognize the custom syntax, we can inject the same transform in the 111 | plugin options: 112 | 113 | ```javascript 114 | new TypedCSSModulesPlugin({ 115 | globPattern: '**/*.css', 116 | postCssPlugins: defaultPlugins => [ 117 | require('postcss-theme')({themePath: './theme'}), 118 | ...defaultPlugins, 119 | ], 120 | }); 121 | ``` 122 | 123 | ## `camelCase?: boolean` 124 | 125 | This field is optional. When set to `true` the CSS field definitions will be emitted using camel case naming conventions. When `undefined` or `false` the CSS field definitions will be emitted verbatim. 126 | 127 | ## `rootDir?: string` 128 | 129 | This field is optional. Project root directory (default: `process.cwd()`). 130 | 131 | ## `searchDir?: string` 132 | 133 | This field is optional. Directory which includes target `*.css` files (default: `'./'`). 134 | 135 | ## `outDir?: string` 136 | 137 | This field is optional. Output directory (default: `option.searchDir`). 138 | 139 | # License 140 | 141 | Copyright (c) 2018 Dropbox, Inc. 142 | 143 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in 144 | compliance with the License. You may obtain a copy of the License at 145 | 146 | ``` 147 | http://www.apache.org/licenses/LICENSE-2.0 148 | ``` 149 | 150 | Unless required by applicable law or agreed to in writing, software distributed under the License is 151 | distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 152 | implied. See the License for the specific language governing permissions and limitations under the 153 | License. 154 | 155 | [1]: https://github.com/Jimdo/typings-for-css-modules-loader 156 | [2]: https://github.com/Megaputer/dts-css-modules-loader 157 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'ts-jest', 3 | testEnvironment: 'node', 4 | watchPathIgnorePatterns: ['/test/cases/*/*.css.d.ts'], 5 | }; 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "typed-css-modules-webpack-plugin", 3 | "version": "0.1.3", 4 | "description": "Generate TypeScript typing declarations for your TypeScript + CSS Modules project.", 5 | "main": "./dist/index.js", 6 | "typing": "./dist/index.d.ts", 7 | "scripts": { 8 | "build": "tsc", 9 | "watch": "tsc --watch", 10 | "prerelease": "npm run build", 11 | "release": "standard-version", 12 | "test": "jest" 13 | }, 14 | "repository": "https://github.com/dropbox/typed-css-modules-webpack-plugin", 15 | "keywords": [ 16 | "typescript", 17 | "css-modules", 18 | "webpack", 19 | "typing" 20 | ], 21 | "author": "Linjie Ding ", 22 | "license": "Apache-2.0", 23 | "bugs": { 24 | "url": "https://github.com/dropbox/typed-css-modules-webpack-plugin/issues" 25 | }, 26 | "homepage": "https://github.com/dropbox/typed-css-modules-webpack-plugin", 27 | "devDependencies": { 28 | "@types/css-modules-loader-core": "^1.1.0", 29 | "@types/glob": "^7.1.3", 30 | "@types/jest": "^26.0.4", 31 | "@types/node": "^14.0.23", 32 | "@types/rimraf": "^3.0.0", 33 | "@types/tapable": "^1.0.6", 34 | "@types/webpack": "^4.41.21", 35 | "css-loader": "^5.0.1", 36 | "jest": "^26.1.0", 37 | "rimraf": "^3.0.2", 38 | "standard-version": "^9.0.0", 39 | "ts-jest": "^26.1.2", 40 | "ts-loader": "^8.0.0", 41 | "typescript": "^3.9.6", 42 | "webpack": "^4.43.0" 43 | }, 44 | "dependencies": { 45 | "chalk": "^4.1.0", 46 | "css-modules-loader-core": "^1.1.0", 47 | "glob": "^7.1.6", 48 | "typed-css-modules": "^0.6.4" 49 | }, 50 | "engines": { 51 | "node": ">= 8" 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | // tslint:disable:no-console no-any 2 | import * as os from 'os'; 3 | import chalk from 'chalk'; 4 | import * as fs from 'fs'; 5 | import * as glob from 'glob'; 6 | import {Plugin as PostCssPlugin} from 'postcss'; 7 | import {Tapable} from 'tapable'; 8 | import {promisify} from 'util'; 9 | import {Compiler} from 'webpack'; 10 | import * as cssModuleCore from 'css-modules-loader-core'; 11 | import DtsCreator from 'typed-css-modules'; 12 | 13 | const globPromise = promisify(glob); 14 | const statPromise = promisify(fs.stat); 15 | 16 | async function writeFile(dtsCreator: DtsCreator, cssFile: string): Promise { 17 | // clears cache so that watch mode generates update-to-date typing. 18 | const content = await dtsCreator.create(cssFile, undefined, true); 19 | await content.writeFile((definition: string) => { 20 | var lines = definition.trim().split(os.EOL); 21 | let attributes = lines.slice(1, lines.length-2); 22 | attributes.sort(); 23 | const newLines = [lines[0], ...attributes, ...lines.slice(lines.length-2), '', '']; 24 | return newLines.join(os.EOL); 25 | }); 26 | } 27 | 28 | async function generateTypingIfNecessary(dtsCreator: DtsCreator, cssFile: string): Promise { 29 | let typingStat: fs.Stats; 30 | try { 31 | typingStat = await statPromise(cssFile + '.d.ts'); 32 | } catch (_) { 33 | // typing does not exist: generate 34 | return writeFile(dtsCreator, cssFile); 35 | } 36 | const cssFileStat = await statPromise(cssFile); 37 | // if file is newer than typing: generate typing 38 | if (cssFileStat.mtime.getTime() > typingStat.mtime.getTime()) { 39 | return writeFile(dtsCreator, cssFile); 40 | } 41 | } 42 | 43 | export interface Options { 44 | readonly globPattern: string; 45 | readonly postCssPlugins?: 46 | | Array> 47 | | ((defaults: ReadonlyArray>) => PostCssPlugin[]); 48 | readonly camelCase?: boolean; 49 | readonly rootDir?: string; 50 | readonly searchDir?: string; 51 | readonly outDir?: string; 52 | } 53 | 54 | export class TypedCssModulesPlugin implements Tapable.Plugin { 55 | private dtsCreator: DtsCreator; 56 | private useIncremental = false; 57 | private globPattern: string; 58 | 59 | constructor({ 60 | globPattern, 61 | postCssPlugins = cssModuleCore.defaultPlugins, 62 | camelCase, 63 | rootDir, 64 | searchDir, 65 | outDir, 66 | }: Options) { 67 | this.globPattern = globPattern; 68 | if (typeof postCssPlugins === 'function') { 69 | postCssPlugins = postCssPlugins(cssModuleCore.defaultPlugins); 70 | } 71 | this.dtsCreator = new DtsCreator({ 72 | rootDir, 73 | searchDir, 74 | outDir, 75 | loaderPlugins: postCssPlugins, 76 | camelCase, 77 | }); 78 | } 79 | 80 | apply(compiler: Compiler) { 81 | compiler.hooks.run.tapPromise('TypedCssModulesPlugin', async () => { 82 | await this.generateCssTypings(this.useIncremental); 83 | }); 84 | // CAVEAT: every time CSS changes, the watch-run is triggered twice: 85 | // - one because CSS changes 86 | // - one because .css.d.ts is added 87 | compiler.hooks.watchRun.tapPromise('TypedCssModulesPlugin', async () => { 88 | try { 89 | // first time this event is triggered, we do a full build instead of incremental build. 90 | await this.generateCssTypings(this.useIncremental); 91 | } catch (err) { 92 | console.log(chalk.bold.red(err.toString())); 93 | } finally { 94 | this.useIncremental = true; 95 | } 96 | }); 97 | } 98 | 99 | private async generateCssTypings(incremental: boolean) { 100 | const files = await globPromise(this.globPattern); 101 | const doTask = incremental ? generateTypingIfNecessary : writeFile; 102 | return Promise.all(files.map(file => doTask(this.dtsCreator, file))); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /test/cases/basic/expected/style.css.d.ts: -------------------------------------------------------------------------------- 1 | declare const styles: { 2 | readonly "foo": string; 3 | readonly "foo-bar": string; 4 | }; 5 | export = styles; 6 | 7 | -------------------------------------------------------------------------------- /test/cases/basic/index.js: -------------------------------------------------------------------------------- 1 | import './style.css'; 2 | -------------------------------------------------------------------------------- /test/cases/basic/style.css: -------------------------------------------------------------------------------- 1 | .foo { 2 | color: rebeccapurple; 3 | } 4 | 5 | .foo-bar { 6 | font-family: monospace; 7 | } 8 | -------------------------------------------------------------------------------- /test/cases/basic/webpack.config.ts: -------------------------------------------------------------------------------- 1 | import {TypedCssModulesPlugin} from '../../../src'; 2 | import * as path from 'path'; 3 | import webpack = require('webpack'); 4 | 5 | const config: webpack.Configuration = { 6 | context: __dirname, 7 | entry: './index', 8 | module: { 9 | rules: [{test: /\.css$/, use: 'css-loader'}], 10 | }, 11 | plugins: [ 12 | new TypedCssModulesPlugin({ 13 | globPattern: path.join(__dirname, '**/*.css'), 14 | }), 15 | ], 16 | }; 17 | module.exports = config; 18 | -------------------------------------------------------------------------------- /test/cases/camelcase/expected/style.css.d.ts: -------------------------------------------------------------------------------- 1 | declare const styles: { 2 | readonly "foo": string; 3 | readonly "fooBar": string; 4 | }; 5 | export = styles; 6 | 7 | -------------------------------------------------------------------------------- /test/cases/camelcase/index.ts: -------------------------------------------------------------------------------- 1 | import * as styles from './style.css'; 2 | console.log(styles.foo); 3 | -------------------------------------------------------------------------------- /test/cases/camelcase/style.css: -------------------------------------------------------------------------------- 1 | .foo { 2 | color: rebeccapurple; 3 | } 4 | 5 | .foo-bar { 6 | font-family: monospace; 7 | } 8 | -------------------------------------------------------------------------------- /test/cases/camelcase/webpack.config.ts: -------------------------------------------------------------------------------- 1 | import {TypedCssModulesPlugin} from '../../../src'; 2 | import * as path from 'path'; 3 | import webpack = require('webpack'); 4 | 5 | const config: webpack.Configuration = { 6 | context: __dirname, 7 | entry: './index.ts', 8 | module: { 9 | rules: [{test: /\.css$/, use: 'css-loader'}, {test: /\.ts$/, use: 'ts-loader'}], 10 | }, 11 | plugins: [ 12 | new TypedCssModulesPlugin({ 13 | globPattern: path.join(__dirname, '**/*.css'), 14 | camelCase: true, 15 | }), 16 | ], 17 | }; 18 | module.exports = config; 19 | -------------------------------------------------------------------------------- /test/cases/typecheck/expected/style.css.d.ts: -------------------------------------------------------------------------------- 1 | declare const styles: { 2 | readonly "foo": string; 3 | readonly "foo-bar": string; 4 | }; 5 | export = styles; 6 | 7 | -------------------------------------------------------------------------------- /test/cases/typecheck/index.ts: -------------------------------------------------------------------------------- 1 | import * as styles from './style.css'; 2 | console.log(styles.foo); 3 | -------------------------------------------------------------------------------- /test/cases/typecheck/style.css: -------------------------------------------------------------------------------- 1 | .foo { 2 | color: rebeccapurple; 3 | } 4 | 5 | .foo-bar { 6 | font-family: monospace; 7 | } 8 | -------------------------------------------------------------------------------- /test/cases/typecheck/webpack.config.ts: -------------------------------------------------------------------------------- 1 | import {TypedCssModulesPlugin} from '../../../src'; 2 | import * as path from 'path'; 3 | import webpack = require('webpack'); 4 | 5 | const config: webpack.Configuration = { 6 | context: __dirname, 7 | entry: './index.ts', 8 | module: { 9 | rules: [{test: /\.css$/, use: 'css-loader'}, {test: /\.ts$/, use: 'ts-loader'}], 10 | }, 11 | plugins: [ 12 | new TypedCssModulesPlugin({ 13 | globPattern: path.join(__dirname, '**/*.css'), 14 | }), 15 | ], 16 | }; 17 | module.exports = config; 18 | -------------------------------------------------------------------------------- /test/webpack-integration.test.ts: -------------------------------------------------------------------------------- 1 | import {unlink, readdirSync, readdir, readFile} from 'fs'; 2 | import * as glob from 'glob'; 3 | import * as path from 'path'; 4 | import * as webpack from 'webpack'; 5 | import {promisify} from 'util'; 6 | import * as rimraf from 'rimraf'; 7 | 8 | const globPromise = promisify(glob); 9 | const unlinkPromise = promisify(unlink); 10 | const readdirPromise = promisify(readdir); 11 | const readFilePromise = promisify(readFile); 12 | const webpackPromise = promisify(webpack); 13 | 14 | const testCases = readdirSync(path.join(__dirname, 'cases')); 15 | const buildOutput = path.join(__dirname, 'build'); 16 | 17 | /** Remove generated .css.d.ts artifacts and Webpack build output. */ 18 | async function removeBuildArtifacts() { 19 | const typingFiles = await globPromise(path.join(__dirname, 'cases/*/*.css.d.ts')); 20 | const unlinks = Promise.all(typingFiles.map(f => unlinkPromise(f))); 21 | rimraf.sync(buildOutput); 22 | await unlinks; 23 | } 24 | 25 | beforeEach(removeBuildArtifacts); 26 | afterAll(removeBuildArtifacts); 27 | 28 | for (const testCase of testCases) { 29 | it(testCase, async () => { 30 | const testDir = path.join(__dirname, 'cases', testCase); 31 | const configFile = path.join(testDir, 'webpack.config.ts'); 32 | 33 | const options: webpack.Configuration = require(configFile); 34 | options.devtool = false; 35 | options.mode = 'development'; 36 | options.output = {path: buildOutput}; 37 | 38 | const stats = await webpackPromise(options); 39 | if (stats.hasErrors()) { 40 | throw Error(stats.toString()); 41 | } 42 | 43 | const expectedDir = path.join(testDir, 'expected'); 44 | for (const file of await readdirPromise(expectedDir)) { 45 | if (!file.endsWith('.css.d.ts')) { 46 | continue; 47 | } 48 | const filePath = path.join(expectedDir, file); 49 | const actualPath = path.join(testDir, file); 50 | expect(await readFilePromise(actualPath)).toStrictEqual(await readFilePromise(filePath)); 51 | } 52 | }); 53 | } 54 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": true, 3 | "compilerOptions": { 4 | "target": "es2017", 5 | "module": "commonjs", 6 | "declaration": true, 7 | "moduleResolution": "node", 8 | "stripInternal": true, 9 | "outDir": "dist", 10 | "strict": true, 11 | "allowSyntheticDefaultImports": true 12 | }, 13 | "include": ["src/**/*"], 14 | "exclude": ["node_modules", "dist"] 15 | } 16 | --------------------------------------------------------------------------------