クロコめも2。

ただのめもー

Windowsで開発はじめるときのメモ

どういうシチュエーションか

複数のWebアプリのプロジェクトを開発していて、ちょこちょこプロジェクトの切り替えが必要。

それぞれのプロジェクトで複数のPowershellのウィンドウが必要

  • スタブサーバを起動させる
  • storybookを起動させる
  • デバッグ実行する
  • gitの操作

そこでプロジェクト毎にbatファイルを用意

中身は

START Powershell -executionpolicy RemoteSigned -noexit -Command cd C:¥{プロジェクトのパス}
START Powershell -executionpolicy RemoteSigned -noexit -Command cd C:¥{プロジェクトのパス}
START Powershell -executionpolicy RemoteSigned -noexit -Command cd C:¥{スタブサーバのパス}
# ↑は開きたい分だけ書いておく

code {vscodeのワークスペースのパス}

こうやっておけば、切り替えたいとき一旦全部Window閉じて作業を始めたいプロジェクトのbatファイルを実行するだけでよくなる。

もっといい書き方はないものか。メモ

複数ダイアログがぽんぽん開くようなWebアプリでWindowの初期表示位置がずれていくタイプのやつ。

初期表示位置を算出するいい方法はないかな

イメージは↓

class positionGenarator {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.originX = x;
        this.originY = y;
        this.count = 0;
    }
    next() {
        const resultX = this.x;
        const resultY = this.y;
        this.count = this.count + 1;
        if (this.count % 5 === 0 && this.count % 10 !== 0) {
            this.y = this.originY;
            this.x = this.x + 24;
        } else if (this.count % 10 === 0) {
            this.x = this.originX;
            this.y = this.originY;
        } else {
            this.x = this.x + 24;
            this.y = this.y + 24;
        }
        return { x: resultX, y: resultY};
    }
}
const a = new positionGenarator(1000, 500);
a.next() // -> {x: 1000, y: 500}
a.next() // -> {x: 1024, y: 524}
a.next() // -> {x: 1048, y: 548}
a.next() // -> {x: 1072, y: 572}
a.next() // -> {x: 1096, y: 596}
a.next() // -> {x: 1120, y: 500}
a.next() // -> {x: 1144, y: 524}
a.next() // -> {x: 1168, y: 548}
a.next() // -> {x: 1192, y: 572}
a.next() // -> {x: 1216, y: 596}
a.next() // -> {x: 1000, y: 500} ここで最初に戻る

generatorを使って書いた方がスマートかと思ったが、いつまでのdoneがtrueにならないgeneratorってなにか気持ち悪いのかな?

NuxtでStorybookつかおうとしたらセットアップで少しつまづくのでメモ

参考にさせていただいたところ

https://nuxtjs.org/guide/typescript/ https://qiita.com/hiropy0123/items/4ee85fdb9b19bc89056f

このメモでいいたかったこと

  • StorybookインストールしたらNuxt起動できなくなるがcore-jsの2系をインストールしたら起動できた。 これ以外は他の記事の内容のまま。

  • Typescriptを使う
  • Prettier使ってみたかった
  • Storybook使えるようになりたい。

環境

  • node 10.16.0
  • npm 6.10.0
  • typescript 3.5.3

ざっくり手順

  • プロジェクト作る
  • 追加のインストール
  • ディレクトリの整理
  • nuxt.config.jsを.tsにして編集する
  • 一旦、初回起動しておく
  • eslintrc.jsを編集する
  • .vscode/settings.jsonを作成、編集して保存時にコードフォーマットがかかるようにする
  • tsconfig.jsonのプロパティを編集する
  • Storybookをインストール
  • 起動できるように修正する
  • storybookのTS用設定

プロジェクト作る、追加のインストール、ディレクトリの整理をばばっと

# create-nuxt-appをインストールする
npm i -g create-nuxt-app

# プロジェクトの作成をする。 Prettierを選ぶ。あとは適当。でも依存関係があるかもしれないので書いておく
create-nuxt-app my-app
? Choose the package manager Yarn
? Choose UI framework Vuetify.js
? Choose custom server framework Express
? Choose Nuxt.js modules Axios
? Choose linting tools ESLint, Prettier
? Choose test framework Jest
? Choose rendering mode Universal (SSR)

# できたらそのディレクトリに移動
cd my-app

# 追加でインストール
yarn add -D @nuxt/typescript
yarn add ts-node
yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser
yarn add -D node-sass sass-loader

# appフォルダを作り移動させておく。Nuxt.jsビギナーズガイドという本の中に利点が書いてあった気がしますが、思い出せない。
mkdir app
mv assets components layouts middleware pages plugins static store app

# ファイル作成(初回起動時に自動で書き込まれるので空ファイルでOK)
touch tsconfig.json

nuxt.config.jsを.tsにして編集する

  • まず枠の部分を公式の指示通り。vuetifyを選んでいたのでそこは併せて書き換える
import NuxtConfiguration from '@nuxt/config';
import colors from 'vuetify/es5/util/colors';

const config: NuxtConfiguration = {
// 既存の設定をそのまま
}
export default config;
  • srcDirを追記しておく
    srcDir: 'app',

一旦、起動

yarn nuxt dev -o

起動が成功したら次に進む

eslintrc.jsを編集する

ここは好みの問題が大きいので他の人を参考にし辛い。

  • .prettierrcがいたらややこしくなるので消す
  • 基本的には推奨設定
  • インデントは4
  • セミコロンは必須にする
module.exports = {
  root: true,
  parser: 'vue-eslint-parser',
  env: {
    browser: true,
    node: true
  },
  parserOptions: {
    parser: '@typescript-eslint/parser'
  },
  extends: [
    '@nuxtjs',
    'plugin:nuxt/recommended',
    'plugin:prettier/recommended',
    'prettier',
    'prettier/vue'
  ],
  plugins: [
    'prettier',
    '@typescript-eslint'
  ],
  // add your custom rules here
  rules: {
   'prettier/prettier': [
       'error', {
           'semi': true,
           'singleQuote': true
       }
   ],
   'no-unused-vars': 'off',
   '@typescript-eslint/no-unused-vars': 'error',
   'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
   'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
   "vue/singleline-html-element-content-newline": "off",
   "vue/no-v-html": "off",
   "vue/html-closing-bracket-spacing": "off",
   "vue/max-attributes-per-line": [2, {
     "singleline": 5,
     "multiline": {
       "max": 1,
       "allowFirstLine": false
     }
   }],
   "indent": ["error", 4],
   "semi-spacing": ["error", {"after": true, "before": false}],
   "semi-style": ["error", "last"],
   "no-extra-semi": "error",
   "no-unexpected-multiline": "error",
   "no-unreachable": "error"
 }
}

.vscode/settings.jsonを作成、編集して保存時にコードフォーマットがかかるようにする

{
  "javascript.format.insertSpaceBeforeFunctionParenthesis": true,
  "typescript.format.insertSpaceBeforeFunctionParenthesis": true,
  "eslint.enable": true,
  "editor.formatOnSave": false,
  "eslint.autoFixOnSave": true,
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    {
      "language": "typescript",
      "autoFix": true
    },
    {
      "language": "vue",
      "autoFix": true
    },
    {
      "language": "vue-html",
      "autoFix": true
    }
  ],
  "eslint.run": "onType",
  "vetur.format.defaultFormatter.js": "prettier",
  "vetur.format.defaultFormatter.css": "prettier",
  "vetur.format.defaultFormatter.less": "prettier",
  "vetur.format.defaultFormatter.postcss": "prettier",
  "vetur.format.defaultFormatter.scss": "prettier",
  "vetur.format.defaultFormatter.stylus": "stylus-supremacy",
  "vetur.format.defaultFormatter.ts": "prettier",
  "vetur.validation.style": true,
  "vetur.validation.template": true
}
  • アプリを起動しなおすとLintのエラーがでるのでエラー出ているファイルを開いて保存し直す。 ※これコマンドで一発でできそうな気がするな。

tsconfig.jsonのプロパティを編集する

    "baseUrl": "./app",

Storybookをインストール

npx -p @storybook/cli sb init --type vue
  • yarn storybookで起動することを確認する
  • yarn nuxt dev -oは起動しない。

起動できるように修正する

下のコマンド叩いてから2系の最新を選んでインストール

yarn add core-js@latest2.6.2

storybookのTS用設定

yarn add -D path fork-ts-checker-webpack-plugin
  • .storybook/webpack.config.js
const path = require('path');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');

module.exports = {
  module: {
    rules: [
      {
        test: /\.ts$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'ts-loader',
            options: {
              appendTsSuffixTo: [/\.vue$/],
              transpileOnly: true
            },
          }
        ]
      },
      {
        test: /\.scss$/,
        use: [
          "style-loader", 
          "css-loader",
          {
            loader: "sass-loader",
            options: {
              importLoaders: 0,
              alias: {
                'assets': path.resolve(__dirname, '../app/assets')
              }
            }
          },
          {
            loader: "sass-resources-loader",
            options: {
              resources: [
                path.resolve(__dirname, '../app/assets/styles/variables/*.scss'),
                path.resolve(__dirname, '../app/assets/styles/common.scss')
              ]
            }
          }
        ]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'file-loader'
      },
      {
        test: /\.pug$/,
        loader: 'pug-plain-loader'
      }
    ]
  },
  plugins: [
    new ForkTsCheckerWebpackPlugin()
  ],
  resolve: {
    extensions: ['.ts', '.js', '.vue', '.json'],
    alias: {
      'static': path.resolve(__dirname, '../app/static'),
      'assets': path.resolve('../app/assets'),
      '@': path.resolve(__dirname, '../app'),
      '~': path.resolve(__dirname, '../app')
    }
  }
};

次回はStorybookでコンポーネント作ってテスト書いてみる。

Nuxt.js v2.8.1 と TypeScript 3.5.3でプロジェクトを作ってみたときのメモ

2019/07/09に公開されているnuxt.jsのバージョンに合わせて内容を更新

準備

  1. nodebrewでnodeのv10.16.0にあげる
  2. npm i -g npmでnpmを最新にしておく
  3. yarn global add typescriptをして3.5.3にあげる

参考にした情報一覧

https://nuxtjs.org/guide/typescript/

プロジェクト生成

  • npx create-nuxt-app myproject
✨  Generating Nuxt.js project in /Users/自分/myproject
? Project name myproject
? Project description My awe-inspiring Nuxt.js project
? Author name myname
? Choose the package manager Yarn
? Choose UI framework Buefy
? Choose custom server framework Express
? Choose Nuxt.js modules Axios
? Choose linting tools ESLint
? Choose test framework Jest
? Choose rendering mode Universal (SSR)

必要なものを追加していく

# できたディレクトリに移動
cd myproject
# typescript用の依存ファイルを追加
yarn add -D @nuxt/typescript
yarn add ts-node
# eslint用の設定を追加
yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser

# ファイル作成(初回起動時に自動で書き込まれるので空ファイルでOK)
touch tsconfig.json

nuxt.config.jsをnuxt.config.tsにリネームして中身を修正する

import NuxtConfiguration from '@nuxt/config'

const config: NuxtConfiguration = {
  // タイプするか `Ctrl + Space` を押すとオートコンプリートできます
  mode: 'universal',
  /*
  ** Headers of the page
  */
  head: {
    title: process.env.npm_package_name || '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: process.env.npm_package_description || '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  /*
  ** Customize the progress-bar color
  */
  loading: { color: '#fff' },
  /*
  ** Global CSS
  */
  css: [
  ],
  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
  ],
  /*
  ** Nuxt.js modules
  */
  modules: [
    // Doc: https://buefy.github.io/#/documentation
    'nuxt-buefy',
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    '@nuxtjs/eslint-module'
  ],
  /*
  ** Axios module configuration
  ** See https://axios.nuxtjs.org/options
  */
  axios: {
  },
  /*
  ** Build configuration
  */
  build: {
    /*
    ** You can extend webpack config here
    */
    extend(config, ctx) {
    }
  }
}

export default config

初回起動(ここでtsconfig.jsonに自動で設定が書き込まれる)

yarn nuxt dev -o

書き込まれたtsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "lib": [
      "esnext",
      "esnext.asynciterable",
      "dom"
    ],
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noImplicitAny": false,
    "noEmit": true,
    "baseUrl": ".",
    "paths": {
      "~/*": [
        "./*"
      ],
      "@/*": [
        "./*"
      ]
    },
    "types": [
      "@types/node",
      "@nuxt/vue-app"
    ]
  }
}

eslintの設定をtypescript用に修正

  • .eslintrc.js
module.exports = {
  root: true,
  env: {
    browser: true,
    node: true
  },
  plugins: ['@typescript-eslint'],
  parserOptions: {
    parser: '@typescript-eslint/parser'
  },
  extends: [
    '@nuxtjs',
    'plugin:nuxt/recommended'
  ],
  // add your custom rules here
  rules: {
    'nuxt/no-cjs-in-config': 'off',
    '@typescript-eslint/no-unused-vars': 'error'
  }
}

IEでおきるバグの小さいサンプル

どんなバグか

input type="text"のplaceholderに日本語を設定しておいて

v-ifで画面表示直後(mounted中)に

  • インプットテキストを消えるようにしておく
  • v-modelに設定されている変数に値を設定する

こうしておくと、IE以外のブラウザでは変数に値が設定されているが、 IEだけ値がリセットされ、空白で上書きされてしまう。

サンプルコード

Nuxtのプロジェクトを作ったときにpagesの中に入っているサンプルの.vueファイルをバグが起きるように書き換える

<template>
  <section class="section">
    <h2 class="title is-3 has-text-grey">
      バグ再現コンポーネント
      <b-icon
        icon="rocket"
        size="is-large"
      />
    </h2>
    <div v-if="isView">これはラベルです。画面表示するとこっちが見えるようになります。{{inputText}}</div>
    <div v-else>これはテキストインプットです。mounted中にv-elseに来ないようになります
      <input type="text" v-model="inputText" placeholder="プレースホルダー文言です。ここをaaとかに書き換えると再現しない"/>
    </div>
    <button @click="change">ラベルとテキストの表示を切り替える確認用ボタン</button>
  </section>
</template>

<script>
export default {
  data() {
    return {
      inputText: '',
      beVisible: false
    }
  },
  mounted() {
    this.inputText = 'IEだけこの変数がリセットされ空白になる'
    this.beVisible = true
  },
  methods: {
    change(e) {
      this.beVisible = !this.beVisible
    }
  },
  computed: {
    isView() {
      return this.beVisible
    }
  }
}
</script>

どうなおすのか

  • placeholderを消す

  • placeholderに日本語を使わない?

  • テキストインプットがmounted前から表示されないようにする(サンプルでいうとbeVisibleの初期値をtrueにする)

    他にもググるといくつか出てくる

    vueのissuesのやりとりに似たようなものも出てくるがvue2.6.10でも再現するのは確認済み

Nuxt2.5.1とTypeScript3.4.1でプロジェクト作ってみるメモ

注意

ただのメモです。これが正解かどうかはまだわかってません。

環境

  • node v10.12.0
  • yarn 1.15.2

スタート

  • yarn global add typescript
  • yarn global add tslint
  • npx create-nuxt-app myproject 好きなものを選ぶ(buefy使いたいから選ぶ)
  • cd myproject
  • yarn.lockを削除
  • node_modulesを削除
  • package.jsonでnuxtのバージョンを2.5.1に書き換えてみる
  • yarn add -D @nuxt/typescript vue-property-decorator
  • echo "{}" > tsconfig.json ファイル作る
  • yarn add -D @typescript-eslint/parser
  • yarn add -D sass-loader node-sass
  • assets/css/main.scssを作って公式ドキュメントにある内容をペースト(https://buefy.org/documentation/customization
  • nuxt.config.jsのcss:[]にassets/css/main.scssを追記。色を変えたりなどして確認
  • yarn nuxt dev -o で起動するとなんかかっこいい。`
  • サンプルを参考に.vueファイルのscript部分をlang="ts"にしてTypescriptに書き換え
  • Propで警告がでるがts-config.json "strictPropertyInitialization": false,を追加してvscode再起動して回避
  • ipでアクセスできるようにnuxt.config.jsに追記 server: { port: 3014, // デフォルト: 3000 host: '0.0.0.0' // デフォルト: localhost, },
  • IE11でも表示できるようにnuxt.config.jsのhead.metaに追記 { hid: 'http-equiv', 'http-equiv': 'X-UA-Compatible', content: 'IE=edge' }