[How to] Setup a Node.js project

Vanilla Javascript, ESLint, and Jest



We will walk through steps to start a new Node.js project. The following are tools including in our project.

  • vanilla javascript (no typescript)
  • eslint for catching bugs
  • jest for running tests

Note that we will use commonjs module instead of esm because jest does not fully support esm yet as of this writing(Feb, 2023).

Steps

  1. Initialize the project.
npm init
  1. Install types for Node.js to make vscode intellisense works properly, e.g. while typing process.env, require(), etc.
npm install --save-dev @types/node
  1. Initialize ESLint.
npm init @eslint/config
  1. Select commonjs as a module, node as a runtime environment, and javascript language (not typescript).
  2. Install Jest. Plus, install its type for vscode intellisense.
npm install --save-dev jest @types/jest
  1. To make ESLint understands Jest's global variables such as test(), expect(), etc., edit .eslintrc.js file.
env: {
	// ...
	jest: true, // <------ add this line
},
  1. Make sure we don't have "type": "module" in package.json file since we want to use commonjs, not esm.
  2. Write javascript as you want, every file is *.js. Test files are in *.test.js pattern.
  3. Use require() and module.exports, not import/export.
  4. Run any js file using node filename.js. Run tests using npx jest.

For Typescript

  • Replace node with ts-node or tsx(preferred)
  • Replace jest with ts-jest or vitest
  • Start with setting tsconfig.json to compile to commonjs