├── .babelrc.json ├── .commitlintrc.json ├── .editorconfig ├── .eslintrc.json ├── .github ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE │ └── bug-report.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── codeql-analysis.yml │ ├── release.yml │ ├── test-code.yml │ └── verify-code-standard.yml ├── .gitignore ├── .husky ├── commit-msg └── pre-commit ├── .lintstagedrc.json ├── .prettierignore ├── .prettierrc.json ├── CHANGELOG.md ├── LICENSE.md ├── README.md ├── jest.config.json ├── package.json ├── src ├── __mocks__ │ ├── glob-files │ │ ├── example-file-01.txt │ │ └── example-file-02.txt │ ├── mock-loader-output.ts │ ├── mock-next-config.ts │ ├── mock-purge-config.ts │ └── webpack-configs │ │ ├── valid-webpack-config-input.ts │ │ ├── valid-webpack-config-output.ts │ │ ├── webpack-config-no-rules.ts │ │ ├── webpkac-config-no-use-array.ts │ │ └── webpkac-config-no-valid-loaders.ts ├── core │ ├── createCustomNextConfig.test.ts │ └── createCustomNextConfig.ts ├── index.ts └── lib │ ├── createGlobPathArray.test.ts │ ├── createGlobPathArray.ts │ ├── createLoader.test.ts │ ├── createLoader.ts │ ├── createWebpackConfig.test.ts │ └── createWebpackConfig.ts ├── tsconfig.json └── types ├── index.d.ts └── index.ts /.babelrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["@babel/preset-env", "@babel/preset-typescript"] 3 | } 4 | -------------------------------------------------------------------------------- /.commitlintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["@commitlint/config-conventional"] 3 | } 4 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | indent_size = 2 7 | indent_style = space 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "eslint:recommended", 4 | "plugin:import/recommended", 5 | "plugin:import/typescript", 6 | "standard", 7 | "semistandard" 8 | ], 9 | 10 | "env": { 11 | "es2021": true, 12 | "jest": true, 13 | "node": true 14 | }, 15 | 16 | "parser": "@typescript-eslint/parser", 17 | 18 | "plugins": [ 19 | "@typescript-eslint", 20 | "import", 21 | "prettier", 22 | "sort-destructure-keys", 23 | "sort-imports-es6-autofix", 24 | "sort-keys-fix" 25 | ], 26 | 27 | "settings": { 28 | "import/resolver": { 29 | "typescript": {} 30 | } 31 | }, 32 | 33 | "rules": { 34 | "@typescript-eslint/no-unused-vars": "error", 35 | "comma-dangle": ["error", "always-multiline"], 36 | "import/first": "error", 37 | "import/newline-after-import": [ 38 | "error", 39 | { 40 | "count": 1 41 | } 42 | ], 43 | "import/no-named-as-default": "off", 44 | "import/no-named-as-default-member": "off", 45 | "no-unused-vars": "off", 46 | "prettier/prettier": "error", 47 | "sort-destructure-keys/sort-destructure-keys": [ 48 | "error", 49 | { 50 | "caseSensitive": true 51 | } 52 | ], 53 | "sort-imports-es6-autofix/sort-imports-es6": [ 54 | "error", 55 | { 56 | "ignoreCase": false, 57 | "ignoreMemberSort": false, 58 | "memberSyntaxSortOrder": ["none", "all", "single", "multiple"] 59 | } 60 | ], 61 | "sort-keys-fix/sort-keys-fix": "error", 62 | "space-before-function-paren": [ 63 | "error", 64 | { 65 | "anonymous": "always", 66 | "asyncArrow": "always", 67 | "named": "never" 68 | } 69 | ] 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Standards 8 | 9 | Examples of behaviour that contributes to a positive environment for our community include: 10 | 11 | - Demonstrating empathy and kindness toward other people 12 | - Being respectful of differing opinions, viewpoints, and experiences 13 | - Giving and gracefully accepting constructive feedback 14 | - Accepting responsibility and apologising to those affected by our mistakes, and learning from the experience 15 | - Focusing on what is best not just for us as individuals, but for the overall community 16 | 17 | Examples of unacceptable behaviour include: 18 | 19 | - The use of sexualised language or imagery, and sexual attention or advances 20 | - Trolling, insulting or derogatory comments, and personal or political attacks 21 | - Public or private harassment 22 | - Publishing others' private information, such as a physical or email address, without their explicit permission 23 | - Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Responsibilities 26 | 27 | Project maintainers are responsible for clarifying and enforcing our standards of acceptable behaviour and will take appropriate and fair corrective action in response to any behaviour that they deem inappropriate, threatening, offensive, or harmful. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behaviour may be reported to the community leaders responsible for enforcement at . All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. 38 | 39 | ## Enforcement Guidelines 40 | 41 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 42 | 43 | ### 1. Correction 44 | 45 | **Community Impact**: 46 | 47 | Use of inappropriate language or other behaviour deemed unprofessional or unwelcome in the community. 48 | 49 | **Consequence**: 50 | 51 | A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behaviour was inappropriate. A public apology may be requested. 52 | 53 | ### 2. Warning 54 | 55 | **Community Impact**: 56 | 57 | A violation through a single incident or series of actions. 58 | 59 | **Consequence**: 60 | 61 | A warning with consequences for continued behaviour. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 62 | 63 | ### 3. Temporary Ban 64 | 65 | **Community Impact**: 66 | 67 | A serious violation of community standards, including sustained inappropriate behaviour. 68 | 69 | **Consequence**: 70 | 71 | A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 72 | 73 | ### 4. Permanent Ban 74 | 75 | **Community Impact**: 76 | 77 | Demonstrating a pattern of violation of community standards, including sustained inappropriate behaviour, harassment of an individual, or aggression toward or disparagement of classes of individuals. 78 | 79 | **Consequence**: 80 | 81 | A permanent ban from any sort of public interaction within the community. 82 | 83 | ## Attribution 84 | 85 | This Code of Conduct is adapted from the [Contributor Covenant](https://contributor-covenant.org/), version 1.4 and 2.0. 86 | 87 | - 1.4 [https://www.contributor-covenant.org/version/1/4/code-of-conduct/code_of_conduct.md](https://www.contributor-covenant.org/version/1/4/code-of-conduct/code_of_conduct.md) 88 | - 2.0 [https://www.contributor-covenant.org/version/2/0/code_of_conduct/code_of_conduct.md](https://www.contributor-covenant.org/version/2/0/code_of_conduct/code_of_conduct.md) 89 | 90 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 91 | 92 | For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are available at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). 93 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Thanks for taking the time to contribute! 4 | 5 | All types of contributions are encouraged and valued. See the [Contents](#contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. 6 | 7 | > If you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about: 8 | > 9 | > - Star the project 10 | > - Tweet about it 11 | > - Refer this project in your project's readme 12 | > - Mention the project at local meetups and tell your friends/colleagues 13 | 14 | ## Contents 15 | 16 | - [Conduct](#conduct) 17 | - [Questions](#questions) 18 | - [Contributing](#contributing) 19 | 20 | ## Conduct 21 | 22 | This project and everyone participating in it is governed by the [Code of Conduct](https://github.com/eels/next-purge-css-modules/blob/main/.github/CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. 23 | 24 | Please report unacceptable behavior to . 25 | 26 | ## Questions 27 | 28 | > If you want to ask a question, we assume that you have read the available [documentation](https://github.com/eels/next-purge-css-modules#readme) in the project's README. 29 | 30 | Before you ask a question, it is best to search for existing [GitHub issues](https://github.com/eels/next-purge-css-modules/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first. 31 | 32 | If you then still feel the need to ask a question and need clarification, we recommend the following: 33 | 34 | - Open an [GitHub issue](https://github.com/eels/next-purge-css-modules/issues/new). 35 | - Provide as much context as you can about what you're running into. 36 | - Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. 37 | 38 | We will then take care of the issue as soon as possible. 39 | 40 | ## Contributing 41 | 42 | > ### Legal Notice 43 | > 44 | > When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license. 45 | 46 | ### Reporting Bugs 47 | 48 | A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible. 49 | 50 | - Make sure that you are using the latest version. 51 | - Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions. 52 | - To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/eels/next-purge-css-modules/issues?q=label%3Abug). 53 | - Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue. 54 | - Collect information about the bug: 55 | - Stack trace (Traceback) 56 | - OS, Platform and Version (Windows, Linux, macOS, x86, ARM) 57 | - Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant. 58 | - Possibly your input and the output 59 | - Can you reliably reproduce the issue? And can you also reproduce it with older versions? 60 | 61 | #### How Do I Submit a Good Bug Report? 62 | 63 | > You must never report security related issues, vulnerabilities or bugs to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to . 64 | 65 | We use GitHub issues to track bugs and errors. If you run into an issue with the project: 66 | 67 | - Open a [GitHub issue](https://github.com/eels/next-purge-css-modules/issues/new). 68 | - Explain the behavior you would expect and the actual behavior. 69 | - Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case. 70 | - Provide the information you collected in the previous section. 71 | 72 | Once it's filed: 73 | 74 | - The project team will label the issue accordingly. 75 | - A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced. 76 | - If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be fixed. 77 | 78 | ### Suggesting Enhancements 79 | 80 | This section guides you through submitting an enhancement suggestion for `next-purge-css-modules`, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions. 81 | 82 | Before Submitting an Enhancement: 83 | 84 | - Make sure that you are using the latest version. 85 | - Read the [documentation](https://github.com/eels/next-purge-css-modules#readme) carefully and find out if the functionality is already covered, maybe by an individual configuration. 86 | - Perform a [search](https://github.com/eels/next-purge-css-modules/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. 87 | - Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library. 88 | 89 | Enhancement suggestions are tracked as [GitHub issues](https://github.com/eels/next-purge-css-modules/issues). 90 | 91 | - Use a **clear and descriptive title** for the issue to identify the suggestion. 92 | - Provide a **step-by-step description of the suggested enhancement** in as many details as possible. 93 | - **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you. 94 | - **Explain why this enhancement would be useful** to `next-purge-css-modules` users. You may also want to point out the other projects that solved it better and which could serve as inspiration. 95 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug-report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: Create a bug report for next-purge-css-modules 4 | labels: bug 5 | --- 6 | 7 | ## Expected Behavior 8 | 9 | - 10 | 11 | ## Actual Behavior 12 | 13 | - 14 | 15 | ## Steps to Reproduce the Problem 16 | 17 | 1. 18 | 19 | ## CodeSandbox Link / Code Snippets 20 | 21 | - 22 | 23 | ## Specifications 24 | 25 | - Version: 26 | - Platform: 27 | - Subsystem: 28 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 3 | - 4 | 5 | ## Type of change 6 | 7 | - [ ] Chore 8 | - [ ] Feature 9 | - [ ] Fix 10 | - [ ] Refactor 11 | - [ ] Revert 12 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | name: CodeQL Analysis 2 | 3 | on: [pull_request, push] 4 | 5 | jobs: 6 | analyse: 7 | name: CodeQL Analysis 8 | runs-on: ubuntu-latest 9 | 10 | permissions: 11 | security-events: write 12 | 13 | strategy: 14 | matrix: 15 | node-version: [16.x] 16 | 17 | steps: 18 | - name: Checkout 19 | uses: actions/checkout@v3 20 | 21 | - name: Initialize CodeQL 22 | uses: github/codeql-action/init@v2 23 | 24 | - name: Use Node.js ${{ matrix.node-version }} 25 | uses: actions/setup-node@v3 26 | with: 27 | node-version: ${{ matrix.node-version }} 28 | 29 | - name: Retrieve Yarn Cache Directory 30 | id: yarn-cache 31 | run: | 32 | echo "::set-output name=dir::$(yarn cache dir)" 33 | 34 | - name: Use Cache 35 | uses: actions/cache@v3 36 | with: 37 | path: ${{ steps.yarn-cache.outputs.dir }} 38 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 39 | restore-keys: ${{ runner.os }}-yarn- 40 | 41 | - name: Install Dependencies 42 | run: | 43 | yarn install --prefer-offline 44 | 45 | - name: Build 46 | run: | 47 | yarn clean 48 | yarn build 49 | 50 | - name: Perform CodeQL Analysis 51 | uses: github/codeql-action/analyze@v2 52 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | workflow_dispatch: 5 | branches: 6 | - main 7 | inputs: 8 | version: 9 | description: Select version to publish 10 | options: 11 | - patch 12 | - minor 13 | - major 14 | required: true 15 | type: choice 16 | 17 | jobs: 18 | release: 19 | name: Release Package to NPM 20 | runs-on: ubuntu-latest 21 | 22 | strategy: 23 | matrix: 24 | node-version: [16.x] 25 | 26 | steps: 27 | - name: Checkout 28 | uses: actions/checkout@v3 29 | with: 30 | fetch-depth: 0 31 | 32 | - name: Set Git User Config Details 33 | run: | 34 | git config --global user.email "liam@liam.codes" 35 | git config --global user.name "Liam Howell" 36 | 37 | - name: Use Node.js ${{ matrix.node-version }} 38 | uses: actions/setup-node@v3 39 | with: 40 | always-auth: true 41 | node-version: ${{ matrix.node-version }} 42 | registry-url: https://registry.npmjs.org 43 | 44 | - name: Retrieve Yarn Cache Directory 45 | id: yarn-cache 46 | run: | 47 | echo "::set-output name=dir::$(yarn cache dir)" 48 | 49 | - name: Use Cache 50 | uses: actions/cache@v3 51 | with: 52 | path: ${{ steps.yarn-cache.outputs.dir }} 53 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 54 | restore-keys: ${{ runner.os }}-yarn- 55 | 56 | - name: Install Dependencies 57 | run: | 58 | yarn install --prefer-offline 59 | 60 | - name: Test Code 61 | run: | 62 | yarn test 63 | 64 | - name: Bump Package Version & Generate Changelog 65 | run: | 66 | yarn version --${{ github.event.inputs.version }} 67 | yarn changelog 68 | 69 | - name: Publish Package 70 | env: 71 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 72 | run: | 73 | yarn publish --non-interactive 74 | 75 | - name: Push Version Update & Tags 76 | env: 77 | github-token: ${{ secrets.GITHUB_TOKEN }} 78 | run: | 79 | VERSION=$(node -p -e "require('./package.json').version") 80 | git add CHANGELOG.md && git commit -m "docs: update v$VERSION changelog" 81 | git push 82 | git push --tags 83 | -------------------------------------------------------------------------------- /.github/workflows/test-code.yml: -------------------------------------------------------------------------------- 1 | name: Test Code 2 | 3 | on: [push] 4 | 5 | jobs: 6 | test: 7 | name: Test Code 8 | runs-on: ubuntu-latest 9 | 10 | strategy: 11 | matrix: 12 | node-version: [16.x] 13 | 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v3 17 | 18 | - name: Use Node.js ${{ matrix.node-version }} 19 | uses: actions/setup-node@v3 20 | with: 21 | node-version: ${{ matrix.node-version }} 22 | 23 | - name: Retrieve Yarn Cache Directory 24 | id: yarn-cache 25 | run: | 26 | echo "::set-output name=dir::$(yarn cache dir)" 27 | 28 | - name: Use Cache 29 | uses: actions/cache@v3 30 | with: 31 | path: ${{ steps.yarn-cache.outputs.dir }} 32 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 33 | restore-keys: ${{ runner.os }}-yarn- 34 | 35 | - name: Install Dependencies 36 | run: | 37 | yarn install --prefer-offline 38 | 39 | - name: Test Code 40 | run: | 41 | yarn test 42 | 43 | - name: Publish To Coveralls 44 | uses: coverallsapp/github-action@master 45 | with: 46 | github-token: ${{ secrets.GITHUB_TOKEN }} 47 | -------------------------------------------------------------------------------- /.github/workflows/verify-code-standard.yml: -------------------------------------------------------------------------------- 1 | name: Verify Code Standard 2 | 3 | on: [push] 4 | 5 | jobs: 6 | verify: 7 | name: Verify Code Standard 8 | runs-on: ubuntu-latest 9 | 10 | strategy: 11 | matrix: 12 | node-version: [16.x] 13 | 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v3 17 | 18 | - name: Use Node.js ${{ matrix.node-version }} 19 | uses: actions/setup-node@v3 20 | with: 21 | node-version: ${{ matrix.node-version }} 22 | 23 | - name: Retrieve Yarn Cache Directory 24 | id: yarn-cache 25 | run: | 26 | echo "::set-output name=dir::$(yarn cache dir)" 27 | 28 | - name: Use Cache 29 | uses: actions/cache@v3 30 | with: 31 | path: ${{ steps.yarn-cache.outputs.dir }} 32 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 33 | restore-keys: ${{ runner.os }}-yarn- 34 | 35 | - name: Install Dependencies 36 | run: | 37 | yarn install --prefer-offline 38 | 39 | - name: Build 40 | run: | 41 | yarn clean 42 | yarn build 43 | 44 | - name: Verify Code Standard 45 | run: | 46 | yarn format 47 | yarn lint 48 | yarn lint:types 49 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Packages 2 | # ---------------------------------------- 3 | 4 | *.tar 5 | *.zip 6 | 7 | # Logs 8 | # ---------------------------------------- 9 | 10 | *.log 11 | 12 | # OS generated files 13 | # ---------------------------------------- 14 | 15 | .DS_Store 16 | .DS_Store? 17 | ._* 18 | .Spotlight-V100 19 | .Trashes 20 | ehthumbs.db 21 | Thumbs.db 22 | 23 | # Lock files 24 | # ---------------------------------------- 25 | 26 | package-lock.json 27 | yarn.lock 28 | 29 | # Dependencies 30 | # ---------------------------------------- 31 | 32 | /node_modules 33 | 34 | # Caches 35 | # ---------------------------------------- 36 | 37 | .eslintcache 38 | 39 | # Compiled resources 40 | # ---------------------------------------- 41 | 42 | /coverage 43 | /dist 44 | -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | . "$(dirname "$0")/_/husky.sh" 4 | 5 | yarn commitlint --edit "$1" 6 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | . "$(dirname "$0")/_/husky.sh" 4 | 5 | yarn lint-staged 6 | -------------------------------------------------------------------------------- /.lintstagedrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "{src,types}/**/*.ts": ["prettier --check", "eslint --cache"] 3 | } 4 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # Markdown 2 | # ---------------------------------------- 3 | 4 | *.md 5 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "always", 3 | 4 | "bracketSpacing": true, 5 | 6 | "jsxSingleQuote": true, 7 | 8 | "printWidth": 100, 9 | 10 | "semi": true, 11 | 12 | "singleQuote": true, 13 | 14 | "trailingComma": "all", 15 | 16 | "quoteProps": "consistent" 17 | } 18 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [v2.0.1](https://github.com/eels/next-purge-css-modules/compare/v2.0.0...v2.0.1) - 2023-12-23 9 | 10 | ### Commits 11 | 12 | - docs: update v2.0.0 changelog [`738629b`](https://github.com/eels/next-purge-css-modules/commit/738629b3a91243e132db8204912a3078c4ff0f20) 13 | - fix: update the module export to the new naming scheme [`5dfe918`](https://github.com/eels/next-purge-css-modules/commit/5dfe9188d20b4e1d13b63cc6d566dfa7eb475305) 14 | 15 | ## [v2.0.0](https://github.com/eels/next-purge-css-modules/compare/v1.1.0...v2.0.0) - 2023-08-10 16 | 17 | ### Merged 18 | 19 | - feat!: support next 13 [`#72`](https://github.com/eels/next-purge-css-modules/pull/72) 20 | 21 | ### Commits 22 | 23 | - add default options in README.md [`72cdeb3`](https://github.com/eels/next-purge-css-modules/commit/72cdeb3a24e1aa09acfb8aead6119af035803239) 24 | - build(deps): bump actions/cache from 2 to 3 [`c2542c8`](https://github.com/eels/next-purge-css-modules/commit/c2542c8d61bea78276ddee142b2265a4f92ef319) 25 | - build(deps): bump actions/checkout from 2 to 3 [`af2eb05`](https://github.com/eels/next-purge-css-modules/commit/af2eb054b63970ffd1a3ea9e90a053c93b064c63) 26 | - build(deps): bump dependabot/fetch-metadata from 1.2.1 to 1.3.0 [`3b42e86`](https://github.com/eels/next-purge-css-modules/commit/3b42e86ffc9b4aa4b41f6387229f8800f2b0be4f) 27 | - build(deps): bump dependabot/fetch-metadata from 1.3.0 to 1.3.1 [`a638b58`](https://github.com/eels/next-purge-css-modules/commit/a638b5840a03a60f50cbaadef5c602b9e0ea2d99) 28 | - build(deps): bump dependabot/fetch-metadata from 1.3.1 to 1.3.3 [`ba5c479`](https://github.com/eels/next-purge-css-modules/commit/ba5c479f29559c92f22a9f5141aceac40906f17b) 29 | - build(deps): bump dependabot/fetch-metadata from 1.3.3 to 1.3.4 [`f5ba038`](https://github.com/eels/next-purge-css-modules/commit/f5ba038f1176c5442e665787e84fbe628f29b821) 30 | - build(deps): bump dependabot/fetch-metadata from 1.3.4 to 1.3.5 [`c0c7489`](https://github.com/eels/next-purge-css-modules/commit/c0c7489eb0c397681a17ad4950b0b6b5631f3bb3) 31 | - build(deps): bump dependabot/fetch-metadata from 1.3.5 to 1.3.6 [`db6476e`](https://github.com/eels/next-purge-css-modules/commit/db6476e2f60d88ed276cc7e9f37ecf7db53d41ab) 32 | - build(deps): bump github/codeql-action from 1 to 2 [`f64d877`](https://github.com/eels/next-purge-css-modules/commit/f64d8771cab7e6b7bfbc6fa5c0bc9643eae5c057) 33 | 34 | ## [v1.1.0](https://github.com/eels/next-purge-css-modules/compare/v1.0.1...v1.1.0) - 2022-02-28 35 | 36 | ### Commits 37 | 38 | - build: remove unneeded dependencies and update eslint config to match [`75a2970`](https://github.com/eels/next-purge-css-modules/commit/75a2970ddb87ca7e424e620a7be199b180decac9) 39 | - build(deps): bump actions/setup-node from 2.5.1 to 3 [`313aa6f`](https://github.com/eels/next-purge-css-modules/commit/313aa6f4425566e10b63ca44ccfc4d7d27b1ada6) 40 | - build(deps): bump dependabot/fetch-metadata from 1.1.1 to 1.2.0 [`1980af0`](https://github.com/eels/next-purge-css-modules/commit/1980af0a5baef09faa949450c1eac636cef67686) 41 | - build(deps): bump dependabot/fetch-metadata from 1.2.0 to 1.2.1 [`7939cac`](https://github.com/eels/next-purge-css-modules/commit/7939cac172751d8f44f3ca29b4e085e9aeed23f6) 42 | - docs: update v1.0.1 changelog [`12850a3`](https://github.com/eels/next-purge-css-modules/commit/12850a30f6bbda50ab8175653fabed6f846a96a9) 43 | - feat: allow extra config options to be passed to purge-css loader [`7c22c9b`](https://github.com/eels/next-purge-css-modules/commit/7c22c9ba94476204be12b07d1930e6d3fda270c7) 44 | 45 | ## [v1.0.1](https://github.com/eels/next-purge-css-modules/compare/v1.0.0...v1.0.1) - 2022-01-17 46 | 47 | ### Commits 48 | 49 | - build: update dependencies [`3d3351a`](https://github.com/eels/next-purge-css-modules/commit/3d3351a2a8a2929e05381347ef0111b8b200b379) 50 | - chore: add src directory to jest roots [`ee6915d`](https://github.com/eels/next-purge-css-modules/commit/ee6915d8a7c3484554f7fee3938d7fa527e62c13) 51 | - chore: remove pass without tests option in test script [`5669560`](https://github.com/eels/next-purge-css-modules/commit/5669560fade4280c42ce7d7e8731a930a0fa395c) 52 | - chore: update next peer dependency bounding version [`fe7b797`](https://github.com/eels/next-purge-css-modules/commit/fe7b7978c8f0e2381a53bdf8734ce0523c10b8ad) 53 | - docs: add badges to readme [`bad996c`](https://github.com/eels/next-purge-css-modules/commit/bad996cc445e9df9294f204a812a8634af6d4c1f) 54 | - docs: add initial usage documentation to readme [`3ca39f2`](https://github.com/eels/next-purge-css-modules/commit/3ca39f2f9b5cfb412f57b91fd0ebb0527faf81f1) 55 | - docs: add keyswords to package.json [`273c8d2`](https://github.com/eels/next-purge-css-modules/commit/273c8d2b907a04639b7474db3f05bdc3b15dad9e) 56 | - docs: update v1.0.0 changelog [`0209cb0`](https://github.com/eels/next-purge-css-modules/commit/0209cb02089074c9a98c54291e71c6b4bd32b8fb) 57 | - fix: add mock clean up code to lib/createLoader test suite [`029de7a`](https://github.com/eels/next-purge-css-modules/commit/029de7a8d9e998d3d366f6c8c216cc063e433c32) 58 | - fix: update .lintstagedrc.json file glob [`0aad6ad`](https://github.com/eels/next-purge-css-modules/commit/0aad6ad35d146776869387cf0ae340a9532bb522) 59 | 60 | ## v1.0.0 - 2022-01-15 61 | 62 | ### Commits 63 | 64 | - build: add initial github workflows [`6a0ddd8`](https://github.com/eels/next-purge-css-modules/commit/6a0ddd886ae3e9b628d2cf1c9540b64a59a6ba92) 65 | - build: update build script [`5b70f2e`](https://github.com/eels/next-purge-css-modules/commit/5b70f2eec1fc8f97d3bbb28685f654a9ec51be66) 66 | - build: update package.json entry point infomation [`b343ac1`](https://github.com/eels/next-purge-css-modules/commit/b343ac11dca8424ad36bfde7315275c94ff0af60) 67 | - chore: add basic issue bug template [`f2b19a1`](https://github.com/eels/next-purge-css-modules/commit/f2b19a1cd98f399aba142f5babd6276a71aff87f) 68 | - chore: add basic pull request template [`97e20fd`](https://github.com/eels/next-purge-css-modules/commit/97e20fdb97e107c6e6dab904d1d0ed189e832884) 69 | - chore: add contributing and conduct documents [`a2697b5`](https://github.com/eels/next-purge-css-modules/commit/a2697b5ebbbda0e489c419d8bfeffc65a7c05c9b) 70 | - chore: update eslint env config [`2a94ec3`](https://github.com/eels/next-purge-css-modules/commit/2a94ec31fdb166a1cf11020783175e53fce75910) 71 | - ci: add code test workflow [`30a263c`](https://github.com/eels/next-purge-css-modules/commit/30a263c5af17f4a683f35cbbb78f527116b4c583) 72 | - ci: add dependabot + auto merge workflow [`b23e265`](https://github.com/eels/next-purge-css-modules/commit/b23e265a6aef52e8f71d51df30360e7fdc9dc100) 73 | - ci: add npm release workflow [`56bb0a2`](https://github.com/eels/next-purge-css-modules/commit/56bb0a2684bce5d67e5b8e1b26005b4fc2781457) 74 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Liam Howell 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |

3 |
4 |
:construction_worker:
5 |
6 |
next-purge-css-modules
7 |
8 |

9 |
10 |
Easily remove unused css-module code in your Next.js application
11 |
12 | 13 | 14 | 15 | 16 |

17 |
yarn add next-purge-css-modules --dev
18 |

19 |
20 | 21 | ## Contents 22 | 23 | - [Installation](#installation) 24 | - [Example Usage](#example-usage) 25 | - [Configuration](#configuration) 26 | - [Usage With Sass](#usage-with-sass) 27 | - [Contributing](#contributing) 28 | - [License](#license) 29 | 30 | ## Installation 31 | 32 | `next-purge-css-modules` can be installed using your favourite JavaScript package manager. 33 | 34 | ```bash 35 | yarn add next-purge-css-modules --dev 36 | ``` 37 | 38 | ```bash 39 | npm install next-purge-css-modules --save-dev 40 | ``` 41 | 42 | ## Example Usage 43 | 44 | If your Next.js project does not already contain one, create a `next.config.js` file in the root of your project directory. 45 | 46 | ```js 47 | const withPurgeCSSModules = require('next-purge-css-modules'); 48 | 49 | /** @type {import('next-purge-css-modules').PurgeConfig} */ 50 | const purgeConfig = { ... }; 51 | 52 | module.exports = withPurgeCSSModules(purgeConfig); 53 | ``` 54 | 55 | You can read more about the advanced configuration of Next.js on the [official documentation site](https://nextjs.org/docs/api-reference/next.config.js/introduction). 56 | 57 | ## Configuration 58 | 59 | This plugin comes preconfigured with some sensible defaults options. However, you are free to alter this configuration to suit your project needs with the use of the custom purge config object via the `next.config.js` file. 60 | 61 | Additionally, you can also pass your custom next config object as the function's second argument. 62 | 63 | ```ts 64 | interface PurgeCSSModulesOptions { 65 | content?: string | string[]; 66 | enableDevPurge?: boolean; 67 | fontFace?: boolean; 68 | keyframes?: boolean; 69 | safelist?: UserDefinedSafelist; 70 | variables?: boolean; 71 | } 72 | ``` 73 | 74 | ```js 75 | const path = require('path'); 76 | const withPurgeCSSModules = require('next-purge-css-modules'); 77 | 78 | /** @type {import('next').NextConfig} */ 79 | const nextConfig = { 80 | ... 81 | }; 82 | 83 | /** @type {import('next-purge-css-modules').PurgeConfig} */ 84 | const purgeConfig = { 85 | content: path.join(__dirname, 'src/**/*.{js,jsx,ts,tsx}'), 86 | enableDevPurge: true, 87 | safelist: ['body', 'html'], 88 | }; 89 | 90 | module.exports = withPurgeCSSModules(purgeConfig, nextConfig); 91 | ``` 92 | 93 | ### `content` 94 | 95 | This option tells `next-purge-css-modules` which files to look through to check for unused css-modules. You can either supply these files as absolute paths or as file path globs and they can either be a single path or an array. 96 | 97 | The default value looks at all JavaScript/TypeScript files in the default Next.js pages directories (`app/**/*.{js,jsx,ts,tsx}`, `pages/**/*.{js,jsx,ts,tsx}`, `src/app/**/*.{js,jsx,ts,tsx}` and `src/pages/**/*.{js,jsx,ts,tsx}`). 98 | 99 | ### `enableDevPurge` 100 | 101 | By default, your css-module code will only be purged when a `production` build is generated. You can set this flag to `true` to enable css-modules purging when running your Next.js project in `development` mode. 102 | 103 | ### `fontFace` 104 | 105 | If there are any unused @font-face rules, setting this flag to `true` will purge them from the final output. By default is `false`. 106 | 107 | ### `keyframes` 108 | 109 | Any unused animation keyframes found within your css-module code will be purged from the final output when this flag is set to `true`. By default is `false`. 110 | 111 | ### `safelist` 112 | 113 | By supplying an array of CSS selectors to the `safelist` option, you can tell `next-purge-css-modules` which selectors you wish to ensure are not purged. By default is `['body', 'html']` 114 | 115 | To read more about the `safelist` configuration option, you can refer to the official [PurgeCSS documentation](https://purgecss.com/configuration.html). 116 | 117 | ### `variables` 118 | 119 | When you are using Custom Properties (CSS variables), or a library using them such as Bootstrap, setting this flag to `true` will purge them from the final output. 120 | 121 | ## Usage With Sass 122 | 123 | `next-purge-css-modules` works directly out of the box with Next.js projects set up to use Sass. 124 | 125 | You can refer to the [official Next.js Sass documentation](https://nextjs.org/docs/basic-features/built-in-css-support#sass-support) to ensure your project is set up correctly. 126 | 127 | ## Contributing 128 | 129 | Thanks for taking the time to contribute! Before you get started, please take a moment to read through our [contributing guide](https://github.com/eels/next-purge-css-modules/blob/main/.github/CONTRIBUTING.md). The focus area for `next-purge-css-modules` right now is fixing potential bugs. 130 | 131 | However, all issues and PRs are welcome! 132 | 133 | ## License 134 | 135 | MIT - see the [LICENSE.md](https://github.com/eels/next-purge-css-modules/blob/main/LICENSE.md) file for details 136 | -------------------------------------------------------------------------------- /jest.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "collectCoverageFrom": ["src/**/*.{ts,tsx}"], 3 | 4 | "moduleDirectories": ["node_modules", "src", "types"], 5 | 6 | "moduleFileExtensions": ["js", "ts", "tsx"], 7 | 8 | "moduleNameMapper": { 9 | "@src/(.*)": "/src/$1", 10 | "@types": "/types" 11 | }, 12 | 13 | "roots": ["/src/"], 14 | 15 | "testEnvironment": "node" 16 | } 17 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "next-purge-css-modules", 3 | "type": "module", 4 | "version": "2.0.1", 5 | "description": "Easily remove unused css-module code in your Next.js application", 6 | "author": "Liam Howell ", 7 | "homepage": "https://github.com/eels/next-purge-css-modules#readme", 8 | "repository": "https://github.com/eels/next-purge-css-modules", 9 | "bugs": "https://github.com/eels/next-purge-css-modules/issues", 10 | "license": "MIT", 11 | "typings": "./types/index.d.ts", 12 | "sideEffects": false, 13 | "main": "./dist/next-purge-css-modules.cjs", 14 | "module": "./dist/next-purge-css-modules.module.js", 15 | "umd:main": "./dist/next-purge-css-modules.umd.js", 16 | "unpkg": "./dist/next-purge-css-modules.umd.js", 17 | "exports": { 18 | ".": { 19 | "umd": "./dist/next-purge-css-modules.umd.js", 20 | "import": "./dist/next-purge-css-modules.module.js", 21 | "require": "./dist/next-purge-css-modules.cjs" 22 | } 23 | }, 24 | "scripts": { 25 | "build": "microbundle --entry ./src/index.ts --raw --no-sourcemap --target node", 26 | "changelog": "auto-changelog -b 10 -l 10 -t keepachangelog --hide-credit --sort-commits subject", 27 | "clean": "rimraf ./dist", 28 | "format": "prettier './{src,types}/**/*.ts' --check", 29 | "format:fix": "yarn format --write", 30 | "lint": "eslint './{src,types}/**/*.ts' --cache", 31 | "lint:fix": "yarn lint --fix", 32 | "lint:types": "tsc --noEmit", 33 | "prepack": "yarn clean && yarn build", 34 | "prepare": "husky install", 35 | "test": "jest --coverage" 36 | }, 37 | "files": [ 38 | "dist/", 39 | "types/index.d.ts", 40 | "LICENSE.md", 41 | "package.json", 42 | "README.md" 43 | ], 44 | "keywords": [ 45 | "css", 46 | "css-modules", 47 | "nextjs", 48 | "nextjs-plugin", 49 | "purgecss", 50 | "scss" 51 | ], 52 | "dependencies": { 53 | "@fullhuman/postcss-purgecss": "^4.1.3", 54 | "glob": "^8.1.0", 55 | "postcss": "^8.4.27", 56 | "postcss-loader": "^7.3.3", 57 | "webpack": "^5.0.0" 58 | }, 59 | "peerDependencies": { 60 | "next": ">=12.0.0" 61 | }, 62 | "devDependencies": { 63 | "@babel/core": "7.18.6", 64 | "@babel/preset-env": "7.18.6", 65 | "@babel/preset-typescript": "7.18.6", 66 | "@commitlint/cli": "17.0.3", 67 | "@commitlint/config-conventional": "17.0.3", 68 | "@types/glob": "7.2.0", 69 | "@types/jest": "28.1.3", 70 | "@types/node": "18.0.0", 71 | "@typescript-eslint/eslint-plugin": "5.30.0", 72 | "@typescript-eslint/parser": "5.30.0", 73 | "auto-changelog": "2.4.0", 74 | "eslint": "8.18.0", 75 | "eslint-config-semistandard": "17.0.0", 76 | "eslint-config-standard": "17.0.0", 77 | "eslint-import-resolver-typescript": "3.1.1", 78 | "eslint-plugin-import": "2.26.0", 79 | "eslint-plugin-n": "15.2.3", 80 | "eslint-plugin-node": "11.1.0", 81 | "eslint-plugin-prettier": "4.1.0", 82 | "eslint-plugin-promise": "6.0.0", 83 | "eslint-plugin-sort-destructure-keys": "1.4.0", 84 | "eslint-plugin-sort-imports-es6-autofix": "0.6.0", 85 | "eslint-plugin-sort-keys-fix": "1.1.2", 86 | "eslint-plugin-standard": "5.0.0", 87 | "husky": "8.0.1", 88 | "jest": "28.1.2", 89 | "jest-environment-jsdom": "29.5.0", 90 | "lint-staged": "13.0.3", 91 | "microbundle": "0.15.0", 92 | "next": "12.0.8", 93 | "prettier": "2.7.1", 94 | "react": "17.0.2", 95 | "react-dom": "17.0.2", 96 | "rimraf": "3.0.2", 97 | "typescript": "4.7.4" 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/__mocks__/glob-files/example-file-01.txt: -------------------------------------------------------------------------------- 1 | // example mock file 2 | -------------------------------------------------------------------------------- /src/__mocks__/glob-files/example-file-02.txt: -------------------------------------------------------------------------------- 1 | // example mock file 2 | -------------------------------------------------------------------------------- /src/__mocks__/mock-loader-output.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | loader: require.resolve('postcss-loader'), 3 | options: { 4 | postcssOptions: () => ({ 5 | config: false, 6 | implementation: require('postcss'), 7 | plugins: [ 8 | [ 9 | '@fullhuman/postcss-purgecss', 10 | { 11 | content: ['example'], 12 | fontFace: false, 13 | keyframes: false, 14 | safelist: ['body', 'html'], 15 | variables: false, 16 | }, 17 | ], 18 | ], 19 | }), 20 | }, 21 | }; 22 | -------------------------------------------------------------------------------- /src/__mocks__/mock-next-config.ts: -------------------------------------------------------------------------------- 1 | import type { NextConfig } from 'next/types/index.d'; 2 | 3 | export default { 4 | compress: false, 5 | env: {}, 6 | } as NextConfig; 7 | -------------------------------------------------------------------------------- /src/__mocks__/mock-purge-config.ts: -------------------------------------------------------------------------------- 1 | import type { PurgeConfig } from '@types'; 2 | 3 | export default { 4 | content: ['example'], 5 | enableDevPurge: false, 6 | fontFace: false, 7 | keyframes: false, 8 | safelist: ['body', 'html'], 9 | variables: false, 10 | } as PurgeConfig; 11 | -------------------------------------------------------------------------------- /src/__mocks__/webpack-configs/valid-webpack-config-input.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | module: { 3 | rules: [ 4 | { 5 | oneOf: [ 6 | { 7 | test: '/*.example$/', 8 | use: [ 9 | { 10 | loader: '/some-other-loader/dist/index.js', 11 | }, 12 | ], 13 | }, 14 | { 15 | test: '/*.module.css$/', 16 | use: [ 17 | { 18 | loader: '/css-loader/dist/index.js', 19 | }, 20 | { 21 | loader: '/postcss-loader/dist/index.js', 22 | }, 23 | ], 24 | }, 25 | { 26 | test: '/*.module.s(a|c)ss$/', 27 | use: [ 28 | { 29 | loader: '/postcss-loader/dist/index.js', 30 | }, 31 | { 32 | loader: '/sass-loader/dist/index.js', 33 | }, 34 | ], 35 | }, 36 | ], 37 | }, 38 | ], 39 | }, 40 | }; 41 | -------------------------------------------------------------------------------- /src/__mocks__/webpack-configs/valid-webpack-config-output.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | module: { 3 | rules: [ 4 | { 5 | oneOf: [ 6 | { 7 | test: '/*.example$/', 8 | use: [ 9 | { 10 | loader: '/some-other-loader/dist/index.js', 11 | }, 12 | ], 13 | }, 14 | { 15 | test: '/*.module.css$/', 16 | use: [ 17 | { 18 | loader: '/css-loader/dist/index.js', 19 | }, 20 | { 21 | loader: '/postcss-loader/dist/index.js', 22 | }, 23 | { 24 | loader: '/custom-postcss-loader/dist/index.js', 25 | }, 26 | ], 27 | }, 28 | { 29 | test: '/*.module.s(a|c)ss$/', 30 | use: [ 31 | { 32 | loader: '/postcss-loader/dist/index.js', 33 | }, 34 | { 35 | loader: '/custom-postcss-loader/dist/index.js', 36 | }, 37 | { 38 | loader: '/sass-loader/dist/index.js', 39 | }, 40 | ], 41 | }, 42 | ], 43 | }, 44 | ], 45 | }, 46 | }; 47 | -------------------------------------------------------------------------------- /src/__mocks__/webpack-configs/webpack-config-no-rules.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | module: { 3 | rules: [], 4 | }, 5 | }; 6 | -------------------------------------------------------------------------------- /src/__mocks__/webpack-configs/webpkac-config-no-use-array.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | module: { 3 | rules: [ 4 | { 5 | oneOf: [ 6 | { 7 | test: '/*.module.css$/', 8 | use: '', 9 | }, 10 | ], 11 | }, 12 | ], 13 | }, 14 | }; 15 | -------------------------------------------------------------------------------- /src/__mocks__/webpack-configs/webpkac-config-no-valid-loaders.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | module: { 3 | rules: [ 4 | { 5 | oneOf: [ 6 | { 7 | test: '/*.example$/', 8 | use: [ 9 | { 10 | loader: '/some-other-loader/dist/index.js', 11 | }, 12 | ], 13 | }, 14 | ], 15 | }, 16 | ], 17 | }, 18 | }; 19 | -------------------------------------------------------------------------------- /src/core/createCustomNextConfig.test.ts: -------------------------------------------------------------------------------- 1 | import createCustomNextConfig from '@src/core/createCustomNextConfig'; 2 | import createWebpackConfig from '@src/lib/createWebpackConfig'; 3 | import mockNextConfig from '@src/__mocks__/mock-next-config'; 4 | import mockPurgeConfig from '@src/__mocks__/mock-purge-config'; 5 | import type { WebpackContext, WebpackFactoryArgs } from '@types'; 6 | 7 | jest.mock('@src/lib/createWebpackConfig', () => { 8 | return jest.fn((config) => ({ ...config })); 9 | }); 10 | 11 | describe('core/createCustomNextConfig', () => { 12 | afterEach(() => { 13 | jest.clearAllMocks(); 14 | }); 15 | 16 | it('should return an object', () => { 17 | const output = createCustomNextConfig(mockPurgeConfig, mockNextConfig); 18 | 19 | expect(output).toBeInstanceOf(Object); 20 | }); 21 | 22 | it('should return an object containing the default config options', () => { 23 | const output = createCustomNextConfig({}, mockNextConfig); 24 | 25 | expect(output).toEqual(expect.objectContaining(mockNextConfig)); 26 | }); 27 | 28 | it('should return an object with a key named `webpack` that has a function value', () => { 29 | const output = createCustomNextConfig(mockPurgeConfig, mockNextConfig); 30 | const outputKeys = Object.keys(output); 31 | 32 | expect(outputKeys).toContain('webpack'); 33 | expect(output.webpack).toBeInstanceOf(Function); 34 | }); 35 | 36 | it('should extend the return object with values provided by the parameter', () => { 37 | const config = { minify: true }; 38 | 39 | expect(createCustomNextConfig({}, {})).not.toEqual(expect.objectContaining(config)); 40 | expect(createCustomNextConfig({}, config)).toEqual(expect.objectContaining(config)); 41 | }); 42 | 43 | it('should call the `webpack` function provided via the parameter if it is a function', () => { 44 | const mockWebpackFunction = jest.fn(); 45 | const mockWebpackArguments = [{}, {}] as unknown as WebpackFactoryArgs; 46 | const output = createCustomNextConfig({}, { webpack: mockWebpackFunction }); 47 | 48 | output.webpack.apply(null, mockWebpackArguments); 49 | 50 | expect(mockWebpackFunction).toHaveBeenCalledWith(...mockWebpackArguments); 51 | }); 52 | 53 | it('should return the standard webpack config when the `webpack` function is called and purge is not enabled', () => { 54 | const config = { devtool: 'eval-cheap-source-map' }; 55 | const context = { config: mockNextConfig, dev: true } as unknown as WebpackContext; 56 | const output = createCustomNextConfig({ enableDevPurge: false }, mockNextConfig); 57 | 58 | expect(output.webpack(config, context)).toEqual(config); 59 | expect(createWebpackConfig).not.toHaveBeenCalled(); 60 | }); 61 | }); 62 | -------------------------------------------------------------------------------- /src/core/createCustomNextConfig.ts: -------------------------------------------------------------------------------- 1 | import createWebpackConfig from '@src/lib/createWebpackConfig'; 2 | import path from 'path'; 3 | import type { NextConfig } from 'next/types/index.d'; 4 | import type { PurgeConfig, WebpackConfig, WebpackContext } from '@types'; 5 | 6 | export const initialDefaultConfig: PurgeConfig = { 7 | content: [ 8 | path.join(process.cwd(), 'app/**/*.{js,jsx,ts,tsx}'), 9 | path.join(process.cwd(), 'pages/**/*.{js,jsx,ts,tsx}'), 10 | path.join(process.cwd(), 'src/app/**/*.{js,jsx,ts,tsx}'), 11 | path.join(process.cwd(), 'src/pages/**/*.{js,jsx,ts,tsx}'), 12 | ], 13 | enableDevPurge: false, 14 | fontFace: false, 15 | keyframes: false, 16 | safelist: ['body', 'html'], 17 | variables: false, 18 | }; 19 | 20 | export default function createCustomNextConfig(purge?: PurgeConfig, next?: NextConfig) { 21 | const resolvedPurgeConfig = { ...initialDefaultConfig, ...purge }; 22 | 23 | return { 24 | ...next, 25 | webpack: function (config: WebpackConfig, context: WebpackContext) { 26 | if (typeof next?.webpack === 'function') { 27 | config = next?.webpack(config, context); 28 | } 29 | 30 | const shouldPurgeCSS = !context.dev || resolvedPurgeConfig?.enableDevPurge; 31 | 32 | return shouldPurgeCSS ? createWebpackConfig(config, resolvedPurgeConfig) : config; 33 | }, 34 | }; 35 | } 36 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from '@src/core/createCustomNextConfig'; 2 | -------------------------------------------------------------------------------- /src/lib/createGlobPathArray.test.ts: -------------------------------------------------------------------------------- 1 | import createGlobPathArray from '@src/lib/createGlobPathArray'; 2 | import path from 'path'; 3 | 4 | describe('lib/createGlobPathArray', () => { 5 | it('should return an array of files matching the input of an array of directory globs', () => { 6 | const glob = [path.join(__dirname, '../__mocks__/glob-files/**/*.txt')]; 7 | 8 | expect(createGlobPathArray(glob)).toEqual([ 9 | path.join(__dirname, '../__mocks__/glob-files/example-file-01.txt'), 10 | path.join(__dirname, '../__mocks__/glob-files/example-file-02.txt'), 11 | ]); 12 | }); 13 | }); 14 | -------------------------------------------------------------------------------- /src/lib/createGlobPathArray.ts: -------------------------------------------------------------------------------- 1 | import glob from 'glob'; 2 | 3 | export default function createGlobPathArray(paths: string[]) { 4 | return paths.reduce((globs, path) => { 5 | return [...globs, ...glob.sync(path, { nodir: true })]; 6 | }, []); 7 | } 8 | -------------------------------------------------------------------------------- /src/lib/createLoader.test.ts: -------------------------------------------------------------------------------- 1 | import createLoader from '@src/lib/createLoader'; 2 | import mockLoaderOutput from '@src/__mocks__/mock-loader-output'; 3 | import mockPurgeConfig from '@src/__mocks__/mock-purge-config'; 4 | 5 | jest.mock('@src/lib/createGlobPathArray', () => jest.fn((paths) => paths)); 6 | jest.mock('postcss', () => jest.fn()); 7 | 8 | describe('lib/createLoader', () => { 9 | afterEach(() => { 10 | jest.clearAllMocks(); 11 | }); 12 | 13 | it('should return an object', () => { 14 | const output = createLoader(mockPurgeConfig); 15 | 16 | expect(typeof output).toBe('object'); 17 | expect(Array.isArray(output)).not.toBeTruthy(); 18 | }); 19 | 20 | it('should return an object of a required shaped', () => { 21 | const output = createLoader(mockPurgeConfig); 22 | const outputKeys = Object.keys(output); 23 | const outputOptionKeys = Object.keys(output.options); 24 | 25 | expect(outputKeys).toEqual(['loader', 'options']); 26 | expect(outputOptionKeys).toEqual(['postcssOptions']); 27 | expect(output.options.postcssOptions).toBeInstanceOf(Function); 28 | 29 | const postcssOptionsOutput = output.options.postcssOptions(); 30 | const postcssOptionsOutputKeys = Object.keys(postcssOptionsOutput); 31 | 32 | expect(postcssOptionsOutputKeys).toEqual(['config', 'implementation', 'plugins']); 33 | }); 34 | 35 | it('should serialize to the same expected output given specific inputs', () => { 36 | expect(JSON.stringify(createLoader(mockPurgeConfig))).toEqual(JSON.stringify(mockLoaderOutput)); 37 | }); 38 | 39 | it('should wrap content path string arguments in an array', () => { 40 | mockPurgeConfig.content = 'example'; 41 | 42 | const output = createLoader(mockPurgeConfig).options.postcssOptions(); 43 | const pluginContent = output.plugins; 44 | 45 | expect(Array.isArray(pluginContent)).toBeTruthy(); 46 | expect(typeof pluginContent[0][0]).toBe('string'); 47 | expect((pluginContent[0][1] as any).content).toEqual(['example']); 48 | }); 49 | 50 | it('should maintain content path array arguments as-is', () => { 51 | const output = createLoader(mockPurgeConfig).options.postcssOptions(); 52 | const pluginContent = output.plugins; 53 | 54 | expect(Array.isArray(pluginContent)).toBeTruthy(); 55 | expect((pluginContent[0][1] as any).content).toEqual(['example']); 56 | }); 57 | 58 | it('should return valid content value if none is provided via the next config', () => { 59 | delete mockPurgeConfig.content; 60 | 61 | const output = createLoader(mockPurgeConfig).options.postcssOptions(); 62 | const pluginContent = output.plugins; 63 | 64 | expect((pluginContent[0][1] as any).content).toEqual([]); 65 | }); 66 | }); 67 | -------------------------------------------------------------------------------- /src/lib/createLoader.ts: -------------------------------------------------------------------------------- 1 | import createGlobPathArray from '@src/lib/createGlobPathArray'; 2 | import type { PurgeConfig } from '@types'; 3 | 4 | export default function createLoader(purgeConfig: PurgeConfig) { 5 | const content = purgeConfig?.content || []; 6 | const contentArray = Array.isArray(content) ? content : [content]; 7 | 8 | return { 9 | loader: require.resolve('postcss-loader'), 10 | options: { 11 | postcssOptions: () => ({ 12 | config: false, 13 | implementation: require('postcss'), 14 | plugins: [ 15 | [ 16 | '@fullhuman/postcss-purgecss', 17 | { 18 | content: createGlobPathArray(contentArray), 19 | fontFace: purgeConfig?.fontFace, 20 | keyframes: purgeConfig?.keyframes, 21 | safelist: purgeConfig?.safelist, 22 | variables: purgeConfig?.variables, 23 | }, 24 | ], 25 | ], 26 | }), 27 | }, 28 | }; 29 | } 30 | -------------------------------------------------------------------------------- /src/lib/createWebpackConfig.test.ts: -------------------------------------------------------------------------------- 1 | import ValidWebpackConfigInput from '@src/__mocks__/webpack-configs/valid-webpack-config-input'; 2 | import ValidWebpackConfigOutput from '@src/__mocks__/webpack-configs/valid-webpack-config-output'; 3 | import WebpackConfigNoRules from '@src/__mocks__/webpack-configs/webpack-config-no-rules'; 4 | import WebpackConfigNoUseArray from '@src/__mocks__/webpack-configs/webpkac-config-no-use-array'; 5 | import WebpackConfigNoValidLoaders from '@src/__mocks__/webpack-configs/webpkac-config-no-valid-loaders'; 6 | import createLoader from '@src/lib/createLoader'; 7 | import createWebpackConfig from '@src/lib/createWebpackConfig'; 8 | import mockPurgeConfig from '@src/__mocks__/mock-purge-config'; 9 | 10 | jest.mock('@src/lib/createLoader', () => { 11 | return jest.fn(() => ({ loader: '/custom-postcss-loader/dist/index.js' })); 12 | }); 13 | 14 | describe('lib/createCustomWebpackConfig', () => { 15 | afterEach(() => { 16 | jest.clearAllMocks(); 17 | }); 18 | 19 | it('should return default config when no valid `oneOf` rules are present', () => { 20 | const config = Object.assign({}, WebpackConfigNoRules); 21 | const output = createWebpackConfig(config, mockPurgeConfig); 22 | 23 | expect(output).toEqual(config); 24 | }); 25 | 26 | it('should return the same input as the output when the no valid `use` array is found', () => { 27 | const config = Object.assign({}, WebpackConfigNoUseArray); 28 | const output = createWebpackConfig(config, mockPurgeConfig); 29 | 30 | expect(output).toEqual(config); 31 | }); 32 | 33 | it('should return the default config when no valid loaders are present', () => { 34 | const config = Object.assign({}, WebpackConfigNoValidLoaders); 35 | const output = createWebpackConfig(config, mockPurgeConfig); 36 | 37 | expect(output).toEqual(config); 38 | }); 39 | 40 | it('should return a modified config when valid loaders are present', () => { 41 | const paths = ['example/path.js']; 42 | const clonedPurgeConfig = { ...mockPurgeConfig, content: paths }; 43 | const config = Object.assign({}, ValidWebpackConfigInput); 44 | const output = createWebpackConfig(config, clonedPurgeConfig); 45 | 46 | expect(output).toEqual(ValidWebpackConfigOutput); 47 | expect(createLoader).toHaveBeenNthCalledWith(2, clonedPurgeConfig); 48 | }); 49 | }); 50 | -------------------------------------------------------------------------------- /src/lib/createWebpackConfig.ts: -------------------------------------------------------------------------------- 1 | import createLoader from '@src/lib/createLoader'; 2 | import type { PurgeConfig, WebpackConfig, WebpackModuleMultiRule } from '@types'; 3 | 4 | export default function createWebpackConfig(config: WebpackConfig, purgeConfig: PurgeConfig) { 5 | const STYLES_LOADER_REGEX = /\/(css|sass)-loader\/(?:cjs|dist|src)/; 6 | const rules = config.module.rules as WebpackModuleMultiRule[]; 7 | const targetRules = rules.find((rule) => rule.oneOf !== undefined); 8 | const stylingRules = targetRules?.oneOf?.filter?.(({ use }) => Array.isArray(use)) || []; 9 | 10 | for (const { test, use } of stylingRules) { 11 | if (!use.some(({ loader }) => STYLES_LOADER_REGEX.test(loader))) { 12 | continue; 13 | } 14 | 15 | const isPureCSSLoader = /\.css\$/.test(test.toString()); 16 | const useEntries = Object.entries(use); 17 | 18 | for (const [index, { loader }] of useEntries) { 19 | if (!STYLES_LOADER_REGEX.test(loader)) { 20 | continue; 21 | } 22 | 23 | if (/\/css-loader\//.test(loader) && isPureCSSLoader) { 24 | use.push(createLoader(purgeConfig)); 25 | } 26 | 27 | if (/\/sass-loader\//.test(loader)) { 28 | use.splice(parseInt(index), 0, createLoader(purgeConfig)); 29 | } 30 | } 31 | } 32 | 33 | return config; 34 | } 35 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowJs": true, 4 | "alwaysStrict": true, 5 | "allowSyntheticDefaultImports": true, 6 | "baseUrl": "./", 7 | "declaration": false, 8 | "declarationDir": null, 9 | "esModuleInterop": true, 10 | "forceConsistentCasingInFileNames": true, 11 | "isolatedModules": true, 12 | "lib": ["dom", "dom.iterable", "esnext"], 13 | "module": "commonjs", 14 | "moduleResolution": "node", 15 | "noEmit": true, 16 | "noFallthroughCasesInSwitch": true, 17 | "noUnusedLocals": true, 18 | "noUnusedParameters": true, 19 | "paths": { 20 | "@src/*": ["src/*"], 21 | "@types": ["./types"] 22 | }, 23 | "resolveJsonModule": true, 24 | "skipLibCheck": true, 25 | "strict": true, 26 | "target": "esnext", 27 | "typeRoots": ["./types", "./node_modules/@types"] 28 | }, 29 | 30 | "include": ["src/**/*", "types/**/*"] 31 | } 32 | -------------------------------------------------------------------------------- /types/index.d.ts: -------------------------------------------------------------------------------- 1 | import type { NextConfig } from 'next/types/index.d'; 2 | import type { UserDefinedSafelist } from '@fullhuman/postcss-purgecss'; 3 | 4 | export type ExtractFnArgs = T extends (...args: infer U) => any ? U : never; 5 | 6 | export interface PurgeConfig { 7 | content?: string | string[]; 8 | enableDevPurge?: boolean; 9 | fontFace?: boolean; 10 | keyframes?: boolean; 11 | safelist?: UserDefinedSafelist; 12 | variables?: boolean; 13 | } 14 | 15 | export type WebpackFactoryArgs = ExtractFnArgs; 16 | 17 | export type WebpackConfig = WebpackFactoryArgs['0']; 18 | 19 | export type WebpackContext = WebpackFactoryArgs['1']; 20 | 21 | export type WebpackModuleLoader = { 22 | loader: string; 23 | }; 24 | 25 | export type WebpackModuleRule = { 26 | test: RegExp; 27 | use: WebpackModuleLoader[]; 28 | }; 29 | 30 | export type WebpackModuleMultiRule = { 31 | oneOf?: WebpackModuleRule[]; 32 | }; 33 | 34 | export default function withPurgeCSSModules(purgeConfig?: PurgeConfig, nextConfig?: NextConfig); 35 | -------------------------------------------------------------------------------- /types/index.ts: -------------------------------------------------------------------------------- 1 | export * from './index.d'; 2 | --------------------------------------------------------------------------------