node.jsnpmnrwl-nxpnpm

NX fails to run root level script using cache


My project is a monorepo used with NX. I try to cache some root level script in my package.json.

I tried to follow this article: https://nx.dev/recipes/running-tasks/root-level-scripts

For this, I have this script in the package.json:

"prettier": "prettier --check **/*.{ts,js,cjs,json,yaml}",

And then if just run pnpm prettier the command succeeds

I use nx@18.1.2 version, and my nx.json is:

{
    "$schema": "./node_modules/nx/schemas/nx-schema.json",
    "workspaceLayout": {
        "appsDir": "apps"
    },
    "tasksRunnerOptions": {
        "default": {
            "runner": "nx/tasks-runners/default",
            "options": {
                "cacheableOperations": ["build", "lint", "type-check", "prettier"]
            }
        }
    },
    "namedInputs": {
        "source": ["{projectRoot}/src/**/*"],
        "jsSource": ["{projectRoot}/src/**/*.{ts,js,cjs}"],
        "reactTsSource": ["{projectRoot}/src/**/*.{ts,tsx}"]
    },
    "targetDefaults": {
        "build": {
            "inputs": ["source"],
            "outputs": ["{projectRoot}/dist", "{projectRoot}/.next"]
        },
        "lint": {
            "inputs": [
                "jsSource",
                "{workspaceRoot}/.eslintrc.cjs",
                "{workspaceRoot}/.eslintignore",
                "{projectRoot}/.eslintrc.cjs",
                "{projectRoot}/.eslintignore"
            ],
            "outputs": []
        },
        "type-check": {
            "inputs": ["reactTsSource", "{projectRoot}/tsconfig.json", "{projectRoot}/tsconfig.base.json", "{workspaceRoot}/tsconfig.base.json"],
            "outputs": []
        },
        "prettier": {
            "inputs": ["**/*.{ts,js,cjs,json,yaml}"],
            "outputs": []
        }
    }
}

Then, to use NX cache with my prettier script, I added this script:

        "prettier:nx": "nx prettier",

Then I run pnpm prettier:nx

But then I get an error:

Error: Both project and target have to be specified

I just don't understand why the output is not the same as I would run Prettier without NX.


Solution

  • You need to add to package.json:

        "nx": {},
    

    Then, change

            "prettier": {
                "inputs": ["**/*.{ts,js,cjs,json,yaml}"],
                "outputs": []
            }
    

    to

            "prettier": {
                "inputs": ["{workspaceRoot}/**/*.{ts,js,cjs,json,yaml}"],
                "outputs": []
            },