お知らせ
現在サイトのリニューアル作業中のため、全体的にページの表示が乱れています。
react-routerでRouteを切る実装例
Env | Ver |
---|---|
React | 17.0.1 |
react-router-dom | 5.2.0 |
TypeScript | 4.1.3 |
index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import './index.scss';
import { BrowserRouter } from 'react-router-dom';
import { RootRoute } from './routes/RootRoute';
// ドメインルート以外にReactを設置する場合に必要
// e.g. `https://www.example.com/react/` に設置する場合 `/react` を設定
const basename = process.env.REACT_APP_BASE_NAME ?? undefined;
ReactDOM.render(
<React.StrictMode>
{/* `useHistory()` 用のDIラッパー */}
<BrowserRouter basename={basename}>
{/* ルーティング設定をまとめたコンポーネント */}
<RootRoute />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
AppRoute.ts
Route
に対して展開できるように記述しておくexport const AppRoute = {
// React のルート定義
root: {
path: '/',
key: '/',
exact: true, // 完全一致
component: App,
},
// 404 定義
notfound: {
component: NotFound,
},
// `/foo` 以下のルーティング定義
foo: {
// `/foo` のルート定義
root: {
path: '/foo',
key: '/foo',
component: FooRoute,
},
// 以下、 `/foo` 配下のページのルーティング定義
hoge: {
path: '/foo/hoge',
key: '/foo/hoge',
component: HogePage,
},
piyo: {
path: '/foo/piyo',
key: '/foo/piyo',
component: PiyoPage,
},
},
};
RootRoute.tsx
export const RootRoute = () => {
return (
{/* `Route` は `Switch` で囲む */}
<Switch>
{/* root */}
<Route {...AppRoute.root} />
{/* foo */}
<Route {...AppRoute.foo.root} />
{/* bar */}
<Route {...AppRoute.bar.root} />
{/* 404 */}
<Route {...AppRoute.notfound} />
</Switch>
);
};
FooRoute.tsx
/foo
階層配下の管理用export const FooRoute = () => {
return (
{/*
`Context` は `Switch` の外に出す
`Switch` の中に `Context` を書くと更に `Switch` でネストする必要がある
*/}
<FooContext.Provider value={FooContextDefault}>
<Switch>
{/* eslint-disable-next-line array-callback-return */}
{Object.entries(AppRoute.foo).map(([idx, route]) => {
if (idx !== 'root') {
/* `'root'` 以外の全ノードを展開 */
return <Route {...route} />;
}
})}
{/* 404 */}
<Route {...AppRoute.notfound} />
</Switch>
</FooContext.Provider>
);
};
自作npmコマンドを蹴る方法のメモ
Env | Ver |
---|---|
Node.js | 12.18.3 |
npm | 6.14.8 |
npm init
とか適当に"bin": {
"my-npm-command": "./index.js"
}
#!/usr/bin/env node
console.log('my-npm-command');
npm link
を叩き、my-npm-command
を実行して動いてればOK
npm unlink
PHPでClassをrequire
せずに使えるやつ
Laravelのrequest()
とかがどうやって呼ばれてるのかを調べていくうちに辿り着いたのでメモがてら
Class
は簡単に読み込めるけど、Function
は一筋縄ではいかなさそう
ついでにClass
に好き勝手プロパティ増やせることも発見した
spl_autoload_registerを使う。Laravelはcomposerが上手いことやってくれてるっぽかった
<?
function regist() {
spl_autoload_register(function() {
require './Hoge.php';
require './Piyo.php';
});
}
適当に用意
<?
class Hoge {
public $hoge;
}
<?
class Piyo {
public $piyo;
}
ついでに好き勝手にプロパティも生やす
<?
require './bootstrap.php';
// ここでクラスをautoloadする
regist();
// どこからも呼んでないけど
$h = new Hoge;
// 生やせる
$h->fuga = "aaa";
$h->hogepiyo = "bbb";
// 使える
$p = new Piyo;
$p->fuga = "aaa";
$p->hogepiyo = "bbb";
var_dump($h, $p);
/*
結果
class Hoge#2 (3) {
public $hoge =>
NULL
public $fuga =>
string(3) "aaa"
public $hogepiyo =>
string(3) "bbb"
}
class Piyo#3 (3) {
public $piyo =>
NULL
public $fuga =>
string(3) "aaa"
public $hogepiyo =>
string(3) "bbb"
}
*/
composer init
でプロジェクトを作成composer require [パッケージ名]
でパッケージを入れるcomposer.jspn
に以下のセクションを作成
"autoload": {
"psr-4": {
"App\\": "src/App" // 名前空間と対応するパス
},
"classmap": [
"src/App" // クラスを読み込むディレクトリのルート
]
}
autoload
やclass_alias
などを設定するbootstrap.php
を適当に作成
bootstrap.php
はエントリポイントからrequire_once
などで読み込無事で有効化するphpunit
を組み込む場合
composer require --dev phpunit/phpunit
でインストールcomposer.json
に以下のセクションを作成 "scripts": {
"test": [
"phpunit --bootstrap bootstrap.php test"
]
}
Env | Ver |
---|---|
Node.js | 12.18.3 |
Jest | 26.4.2 |
以下の実装のときに、parentFunc()
を呼んだ時にchildFunc()
が呼ばれることをテストしたい
function parentFunc() {
console.log('called parentFunc');
childFunc('XXXX');
}
function childFunc(param) {
console.log(`called childFunc ${param}`);
}
テストするためには関数をexportする必要あるが、愚直過ぎて構文的に実行不能になるケース
exports.parentFunc = () => {
console.log('called parentFunc');
// childFuncは別モジュールなので呼べない
childFunc('XXXX');
};
exports.childFunc = (param) => {
console.log(`called childFunc ${param}`);
};
この実装を実行すると期待通り動作するので、一見すると大丈夫そうに見える
function parentFunc() {
console.log('called parentFunc');
childFunc('XXXX');
}
function childFunc(param) {
console.log(`called childFunc ${param}`);
}
module.exports = { parentFunc, childFunc };
しかしこのテストを流すと失敗する
これはparentFunc()
が呼び出すchildFunc()
が下記case2
の中にないため
parentFunc()
のスコープ内にchildFunc()
がいないことが原因
const case2 = require('./case2');
// こうするとjest.spyOn()の第一引数を満たせないので落ちる
// const { parentFunc, childFunc } = require('./case2');
describe('inside call test', function () {
it('parentFunc', function () {
const spy = jest.spyOn(case2, 'parentFunc');
case2.parentFunc();
expect(spy).toHaveBeenCalled();
});
it('childFunc', function () {
const spy = jest.spyOn(case2, 'childFunc');
case2.parentFunc();
// childFuncはcase2に属していないため呼ばれない
expect(spy).toHaveBeenCalled();
});
});
const parentFunc = () => {
console.log('called parentFunc');
// parentFunc()の中にchildオブジェクトを注入することで、
// jestがchildFunc()を認識できるようにする
child.childFunc('XXXX');
};
const child = {
childFunc: (param) => {
console.log(`called childFunc ${param}`);
},
};
// childFuncでなく、childオブジェクトをexportするのが味噌
module.exports = { parentFunc, child };
const case3 = require('./case3');
describe('inside call test', function () {
it('parentFunc', function () {
const spy = jest.spyOn(case3, 'parentFunc');
case3.parentFunc();
expect(spy).toHaveBeenCalled();
});
it('childFunc', function () {
// 注入している側のオブジェクトを参照する
const spy = jest.spyOn(case3.child, 'childFunc');
case3.parentFunc();
// child.childFuncはcase3に属しているため呼ばれる
expect(spy).toHaveBeenCalled();
});
});