כיצד לאפשר תחביר ES6 (ומעבר לו) עם Node ו- Express

ניסית פעם לאפליקציות חזיתיות כתיבה באמצעות תחביר ES6, אבל אז כשאתה החלטת ללמוד פיתוח עורפי עם Node.js ו Express, אתה הבנת שאתה לא יכול להשתמש דברים כאלה import fromו   export default? אם כן, הגעת למקום הנכון! זהו מדריך צעד אחר צעד כיצד להגדיר את סביבות ההתפתחויות והמוצרים שלך, תסריטי ההתקנה, וכבונוס נלמד כיצד להוסיף בדיקות!

תוכן עניינים / סיכום הנושאים

  • איך זה עובד?
  • תנאים מוקדמים
  • התקנת אקספרס
  • הגדרת סקריפטים
  • מַעֲנָק
  • TL; DR

איך זה עובד? מבט ברמה גבוהה על מה שאנחנו צריכים

כדי לאפשר חוויית פיתוח חזיתית בעת פיתוח אפליקציות עורפיות, הנה תצוגה ברמה גבוהה של התהליכים שקורים לפרויקט שלך.

קוד מעביר מ- ES6 + ל- ES5

אנו זקוקים לחבילה המתרגמת תחביר ES6 ומעלה לקוד ES5. קוד ES5 הוא סגנון התחביר JS הניתן לקריאה ל- node.js, כגון module.exportsאו var module = require('module'). שימו לב שבימינו ניתן להשתמש כמעט 99% מתחביר ES6 + ב- Node.js. כאן זורחת החבילה הנקראת babel .

בבל לוקח קובץ js, ממיר בו את הקוד ויוצא לקובץ חדש.

סקריפט שמסיר קבצים

בכל פעם שאנחנו משנים משהו בקוד שלנו, אנו מזינים אותו למשדר, והוא מוציא עותק חדש בכל פעם. לכן אנו זקוקים לסקריפט שמסיר קבצים לפני שנכנס העותק החדש. ובשביל זה יש חבילה קיימת בשם rimraf. Rimraf מוחק קבצים. נדגים זאת בהמשך.

צופה בשינויי קבצים

בעת קידוד ב- Node.js, הפעלה מחדש אוטומטית של השרת שלנו אינה יוצאת מהקופסה בדיוק כמו בעת ביצוע פרויקט שנעשה על גבי יצירת- react-app או vue-cli. לכן נתקין חבילה בשם nodemon, שמבצעת משהו בכל פעם שאנחנו משנים קובץ בקוד שלנו. אנו יכולים למנף את ה- nodemon כדי להפעיל מחדש את השרת בכל פעם שקובץ משתנה.

אז זו התצוגה הגבוהה ביותר של איך זה עובד מתחת למכסה המנוע. עם זאת, נתחיל כיצד עלינו להתקין או להקרין.

תנאים מוקדמים

לפני שנתחיל, עלינו להגדיר תחילה כמה דברים.

  1. ודא שהתקנת את Node.js ו- npm. אני ממליץ להתקין את הגרסה האחרונה של ה- LTS או את הגרסה היציבה הנוכחית. ניתן להתקין אותו באמצעות מקור Node.js או NVM (מנהל גרסאות הצומת)
  2. ידע בסיסי בפקודות המסוף. בכל מקרה רוב הפקודות נמצאות במדריך, כך שלא תצטרכו לדאוג לגביהם.
  3. וודא כי הטרמינל שלך פתוח ועורך הטקסט המועדף עליך מותקן.

זהו, אנחנו טובים ללכת!

התקנת אקספרס

באמצעות הגנרטור אקספרס, ניצור פרויקט חדש עם קוד שנוצר, נעביר כמה קבצים ונתמיר קוד לתחביר ES6. עלינו להמיר אותו בשלב מוקדם זה מכיוון שאנחנו צריכים דרך לאמת אם קוד ה- ES6 שלנו עובד.

הגדרת פרויקט

הפעל פקודה זו במסוף שלך. אתה יכול שם your-project-nameעם השם שאתה אוהב. --no-viewפירושו של דגל שלא נשתמש במנוע תבנית כמו כידון, פליטה או פאג, לאפליקציית השלד Express שלנו.

npx express-generator your-project-name --no-view

לאחר יצירת האפליקציה שלך, עליך לעבור לספריית האפליקציות שלך. עבור מסופי Windows Powershell ו- Linux, השתמש ב:

cd your-project-name

לאחר מכן, פתח את עורך הטקסט שאתה אוהב. מבחינתי, אני פשוט משתמש ב- VSCode אז פשוט יש לי את מסוף ועורך הטקסטים שלי פתוחים במקביל. אבל אתה יכול להשתמש בכל עורך טקסט שאתה רוצה.

התקנת חבילות והעברה ומחיקה של קבצים

לאחר שהפרויקט שנוצר מוכן, עלינו installלתלות ולהעביר כמה תיקיות. הפעל פקודה זו להתקנת אקספרס וחבילות אחרות.

התקנת npm

בזמן שאתה ממתין להתקנת התלות, בצע את הצעדים הבאים.

  • ליצור server/תיקיה
  • שים bin/, app.js, ו routes/בתוך server/התיקייה.
  • שינוי שם www, למצוא binאתwww.js
  • השאר את public/התיקיה בשורש הפרויקט שלך.

מבנה הקובץ שלך ייראה כך:

כעת, מכיוון ששינינו את מבנה הקובץ, סקריפט שרת ההתחלה שלנו לא יעבוד. אבל נתקן את זה בדרך.

המרה לקוד ES6

המרת הקוד שנוצר ל- ES6 זה מעט מייגע, אז פשוט אפרסם את הקוד כאן וארגיש חופשי להעתיק ולהדביק אותו.

קוד ל bin/www.js:

כעת, מכיוון ששינינו את מבנה הקובץ, סקריפט שרת ההתחלה שלנו לא יעבוד. הנה מה שנעשה כדי לתקן את זה. בקובץ package.json שלך, שנה את שם סקריפט ההתחלה כך serverשיימצא באובייקט JSON שנקרא"scripts"

// package.json { "name": "your-project-name", // ....other details "scripts": { "server": "node ./server/bin/www" } }

תראה כי שינינו את נתיב הקובץ ./bin/wwwל ./server/bin/wwwבגלל עברנו קבצים server/. נשתמש בסקריפט ההתחלה בהמשך.

נסה זאת! נסה להפעיל את השרת על ידי הקלדה npm run serverבמסוף שלך ועבור אל localhost:3000הדפדפן שלך.

המרת הקוד ברמה העליונה לשימוש בייבוא ​​ES6

המרת הקוד שנוצר ל- ES6 זה מעט מייגע, אז פשוט אפרסם את הקוד כאן וארגיש חופשי להעתיק ולהדביק אותו.

קוד ל bin/www.js:

// bin/www.js /** * Module dependencies. */ import app from '../app'; import debugLib from 'debug'; import http from 'http'; const debug = debugLib('your-project-name:server'); // ..generated code below.

כמעט כל השינויים שלנו נמצאים רק בחלק העליון והתחתון של הקבצים. אנו משאירים קוד אחר שנוצר כמות שהוא.

קוד עבור routes/index.js ו routes/users.js:

// routes/index.js and users.js import express from 'express'; var router = express.Router(); // ..stuff below export default router;

קוד ל app.js:

// app.js import express from 'express'; import path from 'path'; import cookieParser from 'cookie-parser'; import logger from 'morgan'; import indexRouter from './routes/index'; import usersRouter from './routes/users'; var app = express(); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, '../public'))); app.use('/', indexRouter); app.use('/users', usersRouter); export default app;

בשינה app.js, כי עזבנו public/בשורש הפרויקט, אנחנו צריכים לשנות את הנתיב אחד סטטי אקספרס תיקייה למעלה. שימו לב שהדרך 'public'הפכה '../public'.

app.use(express.static(path.join(__dirname, '../public')));

אוקיי סיימנו עם המרת הקוד! בואו נקבע את התסריטים שלנו עכשיו.

הגדרת סקריפטים

בהגדרת סקריפטים, כל סקריפט מבצע תפקיד אחר. ואנחנו עושים שימוש חוזר בכל סקריפט npm. ולסביבות הפיתוח והייצור שלנו, יש להם תצורה שונה. (כמעט זהה, תראה בהמשך) זו הסיבה שעלינו לחבר את התסריטים שלנו כדי שנוכל להשתמש בהם מבלי להקליד שוב ושוב את אותם דברים.

התקן את 'npm-run-all'

מכיוון שפקודות מסוף מסוימות לא יפעלו ב- Windows cmd, עלינו להתקין חבילה שנקראת npm-run-allכך שסקריפט זה יעבוד בכל סביבה. הפעל פקודה זו בשורש פרויקט המסוף שלך.

npm install --save npm-run-all

התקן את babel, nodemon ו- rimraf

בבל היא העברת JavaScript מודרנית. משדר משחק פירושו שקוד ה- JavaScript המודרני שלך יהפוך לפורמט ישן יותר ש- Node.js יכול להבין. הפעל פקודה זו בשורש פרויקט המסוף שלך. אנו נשתמש בגרסה האחרונה של באבל (בבל 7+).

שים לב שנודמון הוא צופה הקבצים שלנו ורימרף היא חבילות מסיר הקבצים שלנו.

npm install --save @babel/core @babel/cli @babel/preset-env nodemon rimraf

הוספת סקריפט שיגור

Before babel starts converting code, we need to tell it which parts of the code to translate. Note that there are a lots of configuration available, because babel can convert a lot of JS Syntaxes for every different kinds of purpose. Luckily we don’t need to think about that because there’s an available default for that. We are using default config called as preset-env (the one we installed earlier) in our package.json file to tell Babel in which format we are transpiling the code.

Inside your package.json file, create a "babel" object and put this setting.

// package.json { // .. contents above "babel": { "presets": ["@babel/preset-env"] }, }

After this setup we are now ready to test if babel really converts code. Add a script named transpile in your package.json:

// package.json "scripts": { "start": "node ./server/bin/www", "transpile": "babel ./server --out-dir dist-server", }

Now what happened here? First we need to run the cli command babel , specify the files to convert, in this case, the files in server/ and put the transpiled contents in a different folder called dist-server in our project root.

You can test it by running this command

npm run transpile

You’ll see a new folder pop up.

Yay it worked! ✅ As you can see, there’s a folder that has the same folder structure as our server folder but with converted code inside. Pretty cool right? Next step is to run try if our server is running!

Clean script

To have a fresh copy every-time we transpile code into new files, we need a script that removes old files. Add this script to your package.json

"scripts": { "server": "node ./dist-server/bin/www", "transpile": "babel ./server --out-dir dist-server", "clean": "rimraf dist-server" }

This npm script that we made means it removes the folder dist-server/

Now to combine transpile and clean, add a script called build , which combines the two processes.

// scripts "build": "npm-run-all clean transpile"

Running dev script

Now we have a build script, we need to run our dev server. We’ll add a script called dev in our package.json. This takes care of setting our Node Environment to “development”, removing old transpiled code, and replacing it with a new one.

"scripts": { "build": "npm-run-all clean transpile" "server": "node ./dist-server/bin/www", "dev": "NODE_ENV=development npm-run-all build server", "transpile": "babel ./server --out-dir dist-server", "clean": "rimraf dist-server" }

Note here that we’ve changed again the file we are running on our server script. We’re running the file-path with the transpiled code, found in dist-server/.

Adding prod scripts

If we have a dev script that sets the Node Environment to development, we have a prod script that sets it to “production.” We use this configuration when we are deploying. (Heroku, AWS, DigitalOcean, etc..) We’re now adding again our start script and prod script in our package.json again.

"scripts": { "start": "npm run prod" "build": "npm-run-all clean transpile" "server": "node ./dist-server/bin/www", "dev": "NODE_ENV=development npm-run-all build server", "prod": "NODE_ENV=production npm-run-all build server", "transpile": "babel ./server --out-dir dist-server", "clean": "rimraf dist-server" }

We set start script default to prod because start script is being used always by deployment platforms like AWS or Heroku to start a server.

Try either by running npm start or npm run prod .

// package.json ... "nodemonConfig": { "exec": "npm run dev", "watch": ["server/*", "public/*"], "ignore": ["**/__tests__/**", "*.test.js", "*.spec.js"] }, "scripts": { // ... other scripts "watch:dev": "nodemon" }

How about auto-restarting the server whenever a file change?

One final script, in order to complete our development setup. We need to add a file watcher script that runs a command whenever a change is made in a file. Add a JSON Object named “nodemonConfig” in your package.json. This is where we store what we tell the watcher what to do when a file changes.

Also, add a script called watch:dev in your package.json

// package.json ... "nodemonConfig": { "exec": "npm run dev", "watch": ["server/*", "public/*"], "ignore": ["**/__tests__/**", "*.test.js", "*.spec.js"] }, "scripts": { // ... other scripts "watch:dev": "nodemon" }

Nodemon config contains settings related to

  • Which command to run whenever a file changes, in our case npm run dev
  • What folders and files to watch
  • And which files to ignore

More about configuration of nodemon here.

Now that we have our file watcher, you can now just run npm run watch:dev , code, and save your file. and whenever you go to localhost:3000 , you’ll see the changes. Try it out!

Bonus: Add tests!

To add tests in our project, simply install Jest from npm, add a few config, and add a script called test in our package.json

npm i -D jest

Add an object called “jest”, and a test script in your package.json

// package.json ... "jest": { "testEnvironment": "node" }, "scripts": { // ..other scripts "test": "jest" }

Try it out, make a file sample.test.js, write any tests, and run the script!

npm run test

TL;DR

Here are the simplified steps for how to enable ES6 in Node.js. I’ll also include the repo so you can copy and inspect the whole code.

  • Make a new project using express your-project-name terminal command.
  • Move the bin/, routes/ and app into a new folder called src/ , and convert the code into ES6. Also don’t forget to rename bin/www to www.js
  • Install all the dependencies and devDependencies
npm i npm-run-all @babel/cli @babel/core @babel/preset-env nodemon rimraf --save npm i -D jest
  • Add these scripts to your package.json
"scripts": { "start": "npm run prod", "build": "npm-run-all clean transpile", "server": "node ./dist-server/bin/www", "dev": "NODE_ENV=development npm-run-all build server", "prod": "NODE_ENV=production npm-run-all build server", "transpile": "babel ./server --out-dir dist-server", "clean": "rimraf dist-server", "watch:dev": "nodemon", "test": "jest" }
  • Put configurations for babel, nodemon, and jest in your package.json
"nodemonConfig": { "exec": "npm run dev", "watch": [ "server/*", "public/*" ], "ignore": [ "**/__tests__/**", "*.test.js", "*.spec.js" ] }, "babel": { "presets": [ "@babel/preset-env" ] }, "jest": { "testEnvironment": "node" },
  • Test your scripts by running npm run your-script-here
  • You’ll see the complete repo at my github

Notes and disclaimers

Note that this setup may not be proved ideal for all situations, specially for big projects. (like 1k files of code). Transpiling step and deleting might slow down your development environment. Plus, ES Modules, is almost coming to node. But, nevertheless, this is a good eductational material to understand how transipiling runs under the hood like when we are developing front-end apps :)

Conclusion

All right! I hope you learned a lot. Thank you for reading this far.

Happy Coding!

Check the full repo here.

This article is published in freeCodecamp news.

? Twitter - ? freeCodeCamp -  ? Portfolio - ⚛️ Github