برای شناسایی ایرادات در کد و بهبود کیفیت کدها میتوانید از ابزارهای دستهی lint استفاده کنید که تعدادی از معروفترین این ابزارها (jslint ,cpplint ,eslint ,nodelint و ...) هستند.
برای نصب چنین ابزاری مثل lint میتوانید به شکل زیر آن را نصب کنید:
npm install -g eslint
برای اولین بار نیاز است که آماده سازی ابتدایی برای این کتابخانه صورت بگیرد که با دستور زیر قابل انجام است:
eslint --init
? How would you like to configure ESLint? Answer questions about your style ? Are you using ECMAScript 6 features? Yes ? Are you using ES6 modules? Yes ? Where will your code run? Browser, Node ? Do you use CommonJS? No ? Do you use JSX? No ? What style of indentation do you use? Spaces ? What quotes do you use for strings? Double ? What line endings do you use? Windows ? Do you require semicolons? Yes ? What format do you want your config file to be in? JSON Successfully created .eslintrc.json file in D:\ali\electron
eslint . یا eslint index.js
میتوانید این دستور را در در خصوصیت test، در بخش اسکریپت، به شکل زیر وارد کنید:
{ "name": "electron", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "electron .", "test":"eslint ." }, "author": "", "license": "ISC" }
npm test
D:\ali\electron\index.js 1:26 error Strings must use doublequote quotes 16:8 error Strings must use doublequote quotes 19:3 error Expected indentation of 4 space characters but found 2 indent 22:3 error Expected indentation of 4 space characters but found 2 indent ✖ 4 problems (4 errors, 0 warnings)
برای نامگذاری فایلهای js، به جای استفاده از _ از - استفاده کنید. این قاعدهای است که گیت هاب در نامگذاری فایلهای js انجام میدهد. یعنی به جای عبارت dotnet_tips.js از عبارت dotnet-tips.js استفاده کنید. خاطرتان جمع باشد که هیچ فایل جاوااسکرپیتی رسمی در الکترون، خارج از این قاعده نامگذاری نشده است.
سعی کنید از جدیدترین قواعد موجود در ES6 استفاده کنید مانند:
let برای تعریف متغیرها
const برای تعریف ثابت ها
توابع جهتی به جای نوشتن عبارت function
استفاده از template stringها به جای چسباندن رشتهها از طریق عملگر +
برای نامگذاری متغیرها از همان قوانین تعریف شده برای node.js استفاده کنید که شامل موارد زیر است:
- موقعی که یک ماژول را به عنوان یک کلاس استفاده میکنید از متد CamelCase استفاده کنید مثل BrowserWindow
- موقعی که از یک ماژول که حاوی مجموعهای از دستورات و apiها است استفاده میکنید، از قانون mixedCase استفاده کنید مثل app یا globalShortcut
- موقعی که یک api به عنوان خصوصیت یک شیء مورد استفاده قرار میگیرد، از mixedCase استفاده کنید؛ به عنوان مثال win.webContents یا fs.readFileSync
- برای مابقی اشیا مثل دستورات process و یا تگ webview که به شکل متفاوتتری مورد استفاده قرار میگیرند، از همان عنوانهای خودشان استفاده میکنیم.
موقعی که api جدیدی را میسازید و قصد تعریف متدی را دارید بهتر است دو متد برای get و set تعریف شود، نسبت به حالتی که در کتابخانه جی کوئری مورد استفاده قرار میگیرد یعنی عبارتهای زیر
setText('test'); getText();
.text([text]);