瀏覽代碼

feat: TypeScript, ESlint and prettier

LongYinan 5 年之前
父節點
當前提交
25a7f1e2ed
共有 9 個文件被更改,包括 1201 次插入49 次删除
  1. 102 0
      .eslintrc.yml
  2. 1 0
      .prettierignore
  3. 2 2
      __test__/index.spec.js
  4. 1 1
      build.rs
  5. 3 1
      index.js
  6. 23 1
      package.json
  7. 21 21
      src/lib.rs
  8. 12 0
      tsconfig.json
  9. 1036 23
      yarn.lock

+ 102 - 0
.eslintrc.yml

@@ -0,0 +1,102 @@
+parser: '@typescript-eslint/parser'
+
+parserOptions:
+  ecmaFeatures:
+    jsx: true
+  ecmaVersion: 2020
+  sourceType: module
+
+env:
+  browser: true
+  es6: true
+  node: true
+  jest: true
+
+plugins:
+  - import
+  - sonarjs
+
+extends:
+  - eslint:recommended
+  - plugin:sonarjs/recommended
+  - plugin:prettier/recommended
+
+rules:
+  # 0 = off, 1 = warn, 2 = error
+  'space-before-function-paren': 0
+  'no-useless-constructor': 0
+  'no-undef': 2
+  'no-console': [2, { allow: ['error', 'warn', 'info', 'assert'] }]
+  'comma-dangle': ['error', 'only-multiline']
+  'no-unused-vars': 0
+  'no-var': 2
+  'one-var-declaration-per-line': 2
+  'prefer-const': 2
+  'no-const-assign': 2
+  'no-duplicate-imports': 2
+  'no-use-before-define': [2, { 'functions': false, 'classes': false }]
+  'eqeqeq': [2, 'always', { 'null': 'ignore' }]
+  'no-case-declarations': 0
+  'no-restricted-syntax':
+    [
+      2,
+      {
+        'selector': 'BinaryExpression[operator=/(==|===|!=|!==)/][left.raw=true], BinaryExpression[operator=/(==|===|!=|!==)/][right.raw=true]',
+        'message': Don't compare for equality against boolean literals,
+      },
+    ]
+
+  'import/first': 2
+  'import/newline-after-import': 2
+
+  'sonarjs/cognitive-complexity': 0
+  'sonarjs/no-duplicate-string': 0
+  'sonarjs/no-big-function': 0
+  'sonarjs/no-identical-functions': 0
+  'sonarjs/no-small-switch': 0
+
+overrides:
+  - files:
+      - ./**/*.{ts,tsx}
+    rules:
+      'no-unused-vars': [2, { varsIgnorePattern: '^_', argsIgnorePattern: '^_', ignoreRestSiblings: true }]
+
+  - files:
+      - ./**/*{.ts,.tsx}
+    plugins:
+      - '@typescript-eslint'
+    parserOptions:
+      project: ./tsconfig.json
+    rules:
+      # eslint will treat TS type as undefined stuff
+      'no-undef': 0
+
+      # conflict function override
+      'no-dupe-class-members': 0
+
+      '@typescript-eslint/no-unused-vars':
+        [2, { varsIgnorePattern: '^_', argsIgnorePattern: '^_', ignoreRestSiblings: true }]
+      '@typescript-eslint/member-ordering':
+        [
+          2,
+          {
+            default:
+              [
+                'public-static-field',
+                'protected-static-field',
+                'private-static-field',
+                'public-static-method',
+                'protected-static-method',
+                'private-static-method',
+                'public-instance-field',
+                'protected-instance-field',
+                'private-instance-field',
+                'public-constructor',
+                'protected-constructor',
+                'private-constructor',
+                'public-instance-method',
+                'protected-instance-method',
+                'private-instance-method',
+              ],
+          },
+        ]

+ 1 - 0
.prettierignore

@@ -0,0 +1 @@
+target

+ 2 - 2
__test__/index.spec.js

@@ -1,6 +1,6 @@
-const test = require('ava')
+import test from 'ava'
 
-const { sleep, sync } = require('../index')
+import { sleep, sync } from '../index'
 
 test('sync function from native code', (t) => {
   const fixture = 42

+ 1 - 1
build.rs

@@ -1,5 +1,5 @@
 extern crate napi_build;
 
 fn main() {
-  napi_build::setup();
+    napi_build::setup();
 }

+ 3 - 1
index.js

@@ -1,3 +1,5 @@
+const { platform } = require('os')
+
 const { loadBinding } = require('@node-rs/helper')
 
 try {
@@ -7,7 +9,7 @@ try {
   module.exports = loadBinding(__dirname, 'index')
 } catch (e) {
   try {
-    module.exports = require(`@swc-node/core-${platform()}`)
+    module.exports = require(`@napi-rs/package-template-${platform()}`)
   } catch (e) {
     throw new TypeError('Not compatible with your platform. Error message: ' + e.message)
   }

+ 23 - 1
package.json

@@ -19,17 +19,35 @@
   "scripts": {
     "build": "cargo build --release && napi build --platform --release ./index",
     "build:debug": "cargo build && napi --platform ./index",
+    "format": "run-p format:md format:json format:yaml format:source format:rs",
+    "format:md": "prettier --parser markdown --write './**/*.md'",
+    "format:json": "prettier --parser json --write './**/*.json'",
+    "format:rs": "cargo fmt",
+    "format:source": "prettier --config ./package.json --write './**/*.{js,ts}'",
+    "format:yaml": "prettier --parser yaml --write './**/*.{yml,yaml}'",
+    "lint": "eslint . -c ./.eslintrc.yml './**/*.{ts,tsx,js}'",
     "prepublishOnly": "node ./scripts/publish.js",
     "test": "ava",
     "version": "node ./scripts/version.js"
   },
   "devDependencies": {
     "@octokit/rest": "^18.0.4",
+    "@swc-node/register": "^0.4.3",
+    "@typescript-eslint/eslint-plugin": "^3.10.1",
+    "@typescript-eslint/parser": "^3.10.1",
     "ava": "^3.12.1",
     "chalk": "^4.1.0",
+    "eslint": "^7.7.0",
+    "eslint-config-prettier": "^6.11.0",
+    "eslint-plugin-import": "^2.22.0",
+    "eslint-plugin-prettier": "^3.1.4",
+    "eslint-plugin-react": "^7.20.6",
+    "eslint-plugin-react-hooks": "^4.1.0",
+    "eslint-plugin-sonarjs": "^0.5.0",
     "husky": "^4.2.5",
     "lint-staged": "^10.2.13",
     "napi-rs": "^0.2.6",
+    "npm-run-all": "^4.1.5",
     "prettier": "^2.1.1",
     "putasset": "^5.0.3",
     "typescript": "^4.0.2"
@@ -38,11 +56,15 @@
     "@node-rs/helper": "^0.3.1"
   },
   "lint-staged": {
-    "*.@(js|ts|tsx)": ["prettier --write"],
+    "*.@(js|ts|tsx)": ["prettier --write", "eslint -c .eslintrc.yml --fix"],
     "*.@(yml|yaml)": ["prettier --parser yaml --write"],
     "*.md": ["prettier --parser markdown --write"],
     "*.json": ["prettier --parser json --write"]
   },
+  "ava": {
+    "require": ["@swc-node/register"],
+    "extensions": ["ts"]
+  },
   "prettier": {
     "printWidth": 120,
     "semi": false,

+ 21 - 21
src/lib.rs

@@ -16,38 +16,38 @@ register_module!(example, init);
 struct AsyncTask(u32);
 
 impl Task for AsyncTask {
-  type Output = u32;
-  type JsValue = JsNumber;
-
-  fn compute(&mut self) -> Result<Self::Output> {
-    use std::thread::sleep;
-    use std::time::Duration;
-    sleep(Duration::from_millis(self.0 as u64));
-    Ok(self.0 * 2)
-  }
-
-  fn resolve(&self, env: &mut Env, output: Self::Output) -> Result<Self::JsValue> {
-    env.create_uint32(output)
-  }
+    type Output = u32;
+    type JsValue = JsNumber;
+
+    fn compute(&mut self) -> Result<Self::Output> {
+        use std::thread::sleep;
+        use std::time::Duration;
+        sleep(Duration::from_millis(self.0 as u64));
+        Ok(self.0 * 2)
+    }
+
+    fn resolve(&self, env: &mut Env, output: Self::Output) -> Result<Self::JsValue> {
+        env.create_uint32(output)
+    }
 }
 
 fn init(module: &mut Module) -> Result<()> {
-  module.create_named_method("sync", sync_fn)?;
+    module.create_named_method("sync", sync_fn)?;
 
-  module.create_named_method("sleep", sleep)?;
-  Ok(())
+    module.create_named_method("sleep", sleep)?;
+    Ok(())
 }
 
 #[js_function(1)]
 fn sync_fn(ctx: CallContext) -> Result<JsNumber> {
-  let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
+    let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
 
-  ctx.env.create_uint32(argument + 100)
+    ctx.env.create_uint32(argument + 100)
 }
 
 #[js_function(1)]
 fn sleep(ctx: CallContext) -> Result<JsObject> {
-  let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
-  let task = AsyncTask(argument);
-  ctx.env.spawn(task)
+    let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
+    let task = AsyncTask(argument);
+    ctx.env.spawn(task)
 }

+ 12 - 0
tsconfig.json

@@ -0,0 +1,12 @@
+{
+  "compilerOptions": {
+    "target": "ES2018",
+    "strict": true,
+    "moduleResolution": "node",
+    "module": "CommonJS",
+    "noUnusedLocals": true,
+    "noUnusedParameters": true,
+    "esModuleInterop": true,
+    "allowSyntheticDefaultImports": true
+  }
+}

文件差異過大導致無法顯示
+ 1036 - 23
yarn.lock