[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)
eslintfor catching bugsjestfor 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
commonjsas a module,nodeas a runtime environment, andjavascriptlanguage (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.jsfile.
env: {
// ...
jest: true, // <------ add this line
},
- Make sure we don't have
"type": "module"inpackage.jsonfile since we want to usecommonjs, notesm. - Write javascript as you want, every file is
*.js. Test files are in*.test.jspattern. - Use
require()andmodule.exports, notimport/export. - Run any js file using
node filename.js. Run tests usingnpx jest.
For Typescript
- Replace
nodewithts-nodeortsx(preferred) - Replace
jestwithts-jestorvitest - Start with setting
tsconfig.jsonto compile tocommonjs