[How to] Setup a Node.js project
Vanilla Javascript, ESLint, and Jest
Author: Pob Ch |Created: |Updated: |
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 bugsjest
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
- Initialize the project.
npm init
- 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
- Initialize ESLint.
npm init @eslint/config
- Select
commonjs
as a module,node
as a runtime environment, andjavascript
language (nottypescript
). - Install Jest. Plus, install its type for vscode intellisense.
npm install --save-dev jest @types/jest
- To make ESLint understands Jest's global variables such as
test()
,expect()
, etc., edit.eslintrc.js
file.
env: {
// ...
jest: true, // <------ add this line
},
- Make sure we don't have
"type": "module"
inpackage.json
file since we want to usecommonjs
, notesm
. - Write javascript as you want, every file is
*.js
. Test files are in*.test.js
pattern. - Use
require()
andmodule.exports
, notimport
/export
. - Run any js file using
node filename.js
. Run tests usingnpx jest
.
For Typescript
- Replace
node
withts-node
ortsx
(preferred) - Replace
jest
withts-jest
orvitest
- Start with setting
tsconfig.json
to compile tocommonjs