简体   繁体   中英

How to exclude test files in next.js during build?

I am creating next.js app with tests inside the page directory. For this I have added config to next.config.js

const { i18n } = require('./next-i18next.config');

const nextConfig = {
    reactStrictMode: true,
    pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js'],
    styledComponents: true,
    i18n,
};

module.exports = nextConfig;

All my pages have an extension page.tsx. For example Home.page.tsx. My test files are named as follows: Home.spec.tsx.

The problem is, my test files are still included in the build. I did exclude them in my tsconfig file

{
    "compilerOptions": {
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noEmit": true,
        "esModuleInterop": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "jsx": "preserve",
        "incremental": true,
        "types": ["node", "jest", "@testing-library/jest-dom"]
    },
    "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
    "exclude": ["node_modules", "**/*.spec.ts", "**/*.spec.tsx"]
}

I'm not sure what else I should do

Do not put your test inside of the pages directory. If you do so, NextJS will consider this file to be a route of your application, and you will get an error like this when you try to build your app.

You can have your .spec files in any other folder such as /components but not /pages . As per documentation , for testing pages you will need to create a __test__ folder in the root.

Feel free afterwards to also update your exclude setting as:

{
"exclude": ["node_modules"]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM