Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

バックエンドのlintを導入 #2

Closed
takuma-shiraki opened this issue Apr 29, 2024 · 10 comments
Closed

バックエンドのlintを導入 #2

takuma-shiraki opened this issue Apr 29, 2024 · 10 comments

Comments

@takuma-shiraki
Copy link
Contributor Author

takuma-shiraki commented Apr 29, 2024

swcをインストール
https://qiita.com/KokiSakano/items/563e99734850bb5b5723

npm i -D @swc/cli @swc/core

@takuma-shiraki
Copy link
Contributor Author

takuma-shiraki commented Apr 29, 2024

Jestを導入する

参考記事
typescript環境にJestを導入する

# インストール
npm install --save-dev jest @types/jest ts-jest

added 247 packages, and audited 430 packages in 14s

65 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

# 初期化
npx ts-jest config:init


Jest configuration written to "/Users/opm006712/git/github.com/op-tennis/Practice-Backend/jest.config.js".
npm test


> app@1.0.0 test
> jest

  console.log
    Hello, world!

      at Object.<anonymous> (src/app.ts:1:9)

 PASS  test/sum.test.ts
  ✓ adds 1 + 2 to equal 3 (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.72 s
Ran all test suites.

@takuma-shiraki
Copy link
Contributor Author

takuma-shiraki commented Apr 29, 2024

swc はjestより早いらしいので、jestからswc/jestに変更する
最初から、swc/jestを使おうとするとうまくいかなかったので、jestからswc/jestに移行する方法を採用している

@swc/jest

npm i -D @swc/cli @swc/core

touch jest.config.js

const fs = require('fs')

const config = JSON.parse(fs.readFileSync(`${__dirname}/.swcrc`, 'utf-8'))

module.exports = {
    transform: {
        '^.+\\.(t|j)sx?$': ['@swc/jest', { ...config, /* custom configuration in Jest */ }],
    },
}

takuma-shiraki added a commit that referenced this issue Apr 29, 2024
@takuma-shiraki
Copy link
Contributor Author

👆 公式を使う方法はうまくいかんので、Qiitaの記事を参考にする

インストール方法

npx swc ./src/app.ts 
Successfully compiled 1 file with swc.
console.log("Hello, world!");
export function sum(a, b) {
    return a + b;
}
index.js をこのように書いた
const swc = require("@swc/core");

// 第一引数には対象のソースコードを与えます。
// 第二引数には対象のコードが書かれたファイル名やsourcemapを作成することやminifyを行うか否かなどの設定を書きます。
// jscはswcの設定です。結果はPromise<Output>が返されます。このように作成したファイルをnode index.jsで実行するとトランスパイルされたファイルと結果が得られます。
swc
    .transform("src/app.ts", {
        filename: 'app.ts',
        sourceMaps: true,
        minify: true,

        jsc: {
        parser: {
            syntax: "ecmascript",
        },
        transform: {},
        minify: {
            compress: {
            unused: true
            },
            mangle: true,
        },
        },
    })
    .then((output) => {
        console.log(output);
    }
);

// 第一引数には対象のソースコードを与えます。
// 第二引数には設定を記述します。
swc
    .parse("src/app.ts", {
        syntax: "ecmascript",
        comments: false,
        script: true,

        target: "es2022",

    })
    .then((module) => {
        console.log(module);
        console.log(module.body[0]);
    }
);

実行結果👇

node index.js
{
  type: 'Module',
  span: { start: 1, end: 11, ctxt: 0 },
  body: [
    {
      type: 'ExpressionStatement',
      span: [Object],
      expression: [Object]
    }
  ],
  interpreter: null
}
{
  type: 'ExpressionStatement',
  span: { start: 1, end: 11, ctxt: 0 },
  expression: {
    type: 'BinaryExpression',
    span: { start: 1, end: 11, ctxt: 0 },
    operator: '/',
    left: {
      type: 'Identifier',
      span: [Object],
      value: 'src',
      optional: false
    },
    right: {
      type: 'MemberExpression',
      span: [Object],
      object: [Object],
      property: [Object]
    }
  }
}
{
  code: 'src,app.ts;',
  map: '{"version":3,"sources":["app.ts"],"sourcesContent":["src/app.ts"],"names":["src","app","ts"],"rangeMappings":"","mappings":"AAAAA,IAAIC,IAAIC,EAAE"}'
}

takuma-shiraki added a commit that referenced this issue Apr 29, 2024
・npm testを実行時にテストが失敗する
・ts-jestの時からソースコードに差分がほぼ無いのに落ちている理由がわからない
@takuma-shiraki
Copy link
Contributor Author

console.log("Hello, world!")
export function sum(a:any, b:any) {
    return a + b;
}

型定義をするとエラーが出るが、下記のように型定義がされていないと成功する

console.log("Hello, world!")
export function sum(a, b) {
    return a + b;
}
npm test

> app@1.0.0 test
> jest

  console.log
    Hello, world!

      at Object.log (src/app.ts:1:9)

 PASS  test/sum.test.ts
  ✓ adds 1 + 2 to equal 3 (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.121 s
Ran all test suites.

@takuma-shiraki
Copy link
Contributor Author

COPILTくんに聞いてみた
Jestを使ったテスト高速化のため、ts-jestではなく、@swc/jestを使ってみたら予想以上に速かった話の記事を参考に下記のように変更するとうまく行った。

.swcrc

{
  "$schema": "https://json.schemastore.org/swcrc",
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "dynamicImport": false,
      "decorators": false
    },
    "target": "es2022",
    "loose": false,
    "externalHelpers": false
  },
  "minify": false
}


@swc/core@swc/jestのバージョンは最新のものを使用しているようですね。

エラーメッセージから見るに、Syntax Errorが発生している原因は、@swc/jestがTypeScriptの構文を正しく解釈できていない可能性があります。これは、@swc/jestの設定が不適切であるか、もしくは@swc/jestがまだ完全にTypeScriptの構文をサポートしていない可能性があります。

解決策としては、以下の手順を試してみてください:

1. jest.config.jsファイルで、@swc/jestの設定を確認します。以下のように設定されていることを確認してください¹:

module.exports = {
    transform: {
        '^.+\\.(t|j)sx?$': '@swc/jest',
    },
}

2. .swcrcという設定ファイルを作成し、jsc.parser.syntaxtypescriptに設定します²。以下のような設定になります:

{
    "$schema": "https://json.schemastore.org/swcrc",
    "jsc": {
        "parser": {
            "syntax": "typescript",
            "dynamicImport": false,
            "decorators": false
        },
        "target": "es2022",
        "loose": false,
        "externalHelpers": false
    },
    "minify": false
}
  1. それでも問題が解決しない場合は、@swc/jestの代わりにts-jestを使用することを検討してみてください。@swc/jestは高速なテスト実行を目指していますが、まだ全てのTypeScriptの機能を完全にサポートしていない可能性があります。

これらの手順を試してみて、それでも問題が解決しない場合は、詳しい情報を教えていただければと思います。よろしくお願いいたします。🙏

ソース: Bing との会話 2024/5/12
(1) @swc/jest – SWC. https://swc.rs/docs/usage/jest.
(2) Jestを使ったテスト高速化のため、ts-jestではなく、@swc/jestを .... https://qiita.com/Kodak_tmo/items/f0ced5da16b45992a4c6.
(3) Jest with swc, Cannot use 'import.meta' outside a module #7636. swc-project/swc#7636.
(4) swc/jest cant use env with jsc.target · Issue #7759 · swc .... swc-project/swc#7759.
(5) Test suite failed to run error: Expected ';', '}' or #83 - GitHub. swc-project/jest#83.
(6) undefined. https://json.schemastore.org/swcrc.

@takuma-shiraki
Copy link
Contributor Author

@takuma-shiraki
Copy link
Contributor Author

https://docs.github.com/ja/actions/hosting-your-own-runners/managing-self-hosted-runners/managing-access-to-self-hosted-runners-using-groups

macOS
ARM64

Download

# Create a folder
$ mkdir actions-runner && cd actions-runner
# Download the latest runner package
$ curl -o actions-runner-osx-arm64-2.316.1.tar.gz -L https://github.com/actions/runner/releases/download/v2.316.1/actions-runner-osx-arm64-2.316.1.tar.gz
# Optional: Validate the hash
$ echo "75129881e1b80857d235d95a390106470536f5669354cb26af8651861398fa97  actions-runner-osx-arm64-2.316.1.tar.gz" | shasum -a 256 -c
# Extract the installer
$ tar xzf ./actions-runner-osx-arm64-2.316.1.tar.gz

Configure

# Create the runner and start the configuration experience
$ ./config.sh --url https://github.com/op-tennis/Practice-Backend --token BBADDYBO76DGDFEXYHIJOU3GIDKI2
# Last step, run it!
$ ./run.sh

Using your self-hosted runner

# Use this YAML in your workflow file for each job
runs-on: self-hosted

takuma-shiraki added a commit that referenced this issue May 12, 2024
@takuma-shiraki
Copy link
Contributor Author

swc/testを使うための設定ファイルなどがないので、テスト失敗する

テスト結果
https://github.com/op-tennis/Practice-Backend/actions/runs/9051914037/job/24869000082#step:7:10

@takuma-shiraki
Copy link
Contributor Author

testが実行できたのでクローズ
https://github.com/op-tennis/Practice-Backend/actions/runs/9051973014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant