To use both JavaScript (.js) and TypeScript (.ts) in a Next.js project, follow these steps:
1. Set Up a Next.js Project
If you don’t already have a Next.js project, create one by running:
npx create-next-app my-next-app
2. Add TypeScript Support
- Navigate to your project directory:
cd my-next-app - Install TypeScript and required types:
npm install --save-dev typescript @types/react @types/node - Create an empty
tsconfig.jsonfile in the root of your project:touch tsconfig.json - Run the development server:
npm run devNext.js will automatically detect thetsconfig.jsonfile and set it up for you with default settings. The file will be populated with a basic configuration.
3. Mix JavaScript and TypeScript Files
- You can now write files in
.js,.jsx,.ts, and.tsxextensions. Next.js supports mixing these file types seamlessly.
4. Update the tsconfig.json for Compatibility
If needed, you can configure tsconfig.json to allow JavaScript files:
{
"compilerOptions": {
"allowJs": true,
"jsx": "preserve",
"target": "es5",
"module": "esnext",
"strict": true,
"moduleResolution": "node",
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
},
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx"],
"exclude": ["node_modules"]
}
The allowJs option enables JavaScript files in a TypeScript project.
5. Using JavaScript and TypeScript Together
- JavaScript Example (
pages/index.js):
export default function Home() {
return <h1>Hello from JavaScript!</h1>;
}
- TypeScript Example (
pages/about.tsx):
import React from 'react';
const About: React.FC = () => {
return <h1>Hello from TypeScript!</h1>;
};
export default About;
6. Linting (Optional)
To ensure consistent coding standards, install ESLint and configure it to support both JavaScript and TypeScript:
npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
7. Handling TypeScript Errors
If you encounter TypeScript errors, you can temporarily bypass them using // @ts-ignore above the problematic line. However, this should be avoided in production code.
// @ts-ignore
const message = "This is allowed temporarily.";
Conclusion
Next.js supports both JavaScript and TypeScript out of the box, and you can mix them as needed. TypeScript enhances the development experience by adding static typing, while JavaScript can be used for quick prototyping or legacy code integration.