Using JavaScript and TypeScript Together in a Next.js Project

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

  1. Navigate to your project directory: cd my-next-app
  2. Install TypeScript and required types: npm install --save-dev typescript @types/react @types/node
  3. Create an empty tsconfig.json file in the root of your project: touch tsconfig.json
  4. Run the development server: npm run dev Next.js will automatically detect the tsconfig.json file 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 .tsx extensions. 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.

Template literals | Template strings

Template literals in ES6 (EcmaScript) allows us to embed expressions to our string literals. We can use multi-line strings and string interpolation features with them.

Template literals are enclosed by the back-tick (` `) instead of double or single quotes.

var message = `single line string`;
console.log(message);

// single line string

We can include place holders for string substitution using ${ } syntax

var expression = "place holder"; // string substitution
console.log(`this is a text with ${expression} in a line`);

// this is a text with place holder in a line

We can directly use expression interpolation to embed inline math

var a = 5;
var b = 5;

console.log(`the addition of a+b = ${a+b}`);
// the addition of a+b = 10

We can also call functions and use member functions in strings

function sample() { return "text from sample method"; }

console.log(`yes! ${sample()} and i am in uppercase`.toUpperCase());

// YES! TEXT FROM SAMPLE METHOD AND I AM IN UPPERCASE

The above code retrieves data from sample() method and converts it to uppercase in run-time.

Multiline Strings

We can achieve multi line strings, previously we used to insert new line character in our string

console.log(`First line
Second line`);
// First line 
// Second line

Raw strings

The special raw property, available on the first function argument of tagged template literals, allows you to access the raw strings as they were entered.

String.raw`Hi \n ${2+3}!`;
// "Hi \n 5!"

Tagged template literals

A more advanced form of template literals are tagged template literals. With them we able to modify the output of template literals using a function. The first argument contains an array of string literals. The second, and each argument after the first one, are the values of the processed substitution expressions. We can use any name to our function.

var a = 1;
var b = 2;

function tag(strings, ...values) {
 console.log(strings[0]); // "One "
 console.log(strings[1]); // " Two"
 console.log(strings[2]); // " Three"
 console.log(values[0]); // 1
 console.log(values[1]); // 2
}

tag`One ${ a } Two ${ b } Three`;

// One 
// Two 
// Three
// 1
// 2

Happy exploring EcmaScript 🙂