웹팩+바벨을 이용해서 RPG cool 뮤직비디오 플러그인을 써봤던 그 1.

필자는 완전한 초보자이고 자바스크립트는 약간 쓴 정도의 취미 프로그래머이기 때문에 오류와 부족한 점이 있다.눈에 띄는 점이 있으면 지적해 주세요.
또 웹팩, 배벨, ES2015, npm, git 등에 대해 설명하지 말아야 한다.

작업 환경


RPG 쿨 뮤직비디오 1.3.4
Windows10 64bit
Node.js 7.3.0
npm 3.10.10

문제의식


시크한 뮤직비디오 플러그인을 쓸 때 ES5로 힘들게 썼다.1 플러그인 1 파일이 너무 커서 힘들어요.

해본 일


여러 ES 2015 소스는 웹 팩+바벨에서 시크한 뮤직비디오의 플러그인으로 구축할 수 있다.
겸사겸사 모차 ESLight ESDoc도 가입했다.이것들은 다음에 쓰세요.( 쓰다 )

메시지


만들 플러그인


예를 들어 나는 고양이가 인사하는 플러그인을 만들고 싶다.
* 고양이는'이름'과'메시지'가 있다
*미리 여러 마리의 고양이 데이터 등록
* 플러그인 명령CatGreet id id 고양이의 안부 표시
원래 고양이의 데이터는 json으로 읽지만 간단하게 하기 위해 플러그인에 직접 씁니다.
이렇게 움직여.

평범하게 쓰다


나는 아래의 코드가 되는 것과 같은 일반적인 방법으로 쓰고 싶다.이 정도 내용이라면 컷을 반1으로 잘라내는 건 의미가 없지만, 조금 복잡한 일을 하려면 직접 만든 반을 여럿 준비해 두는 것도 좋을 것 같다.
CatGreetingPlugin.js
//=============================================================================
// CatGreetingPlugin.js
//=============================================================================

/*:
 * @plugindesc 猫が挨拶してくれるプラグイン
 * @author betto
 *
 * @help
 *
 * プラグインコマンド:
 *   CatGreet id # id番目の猫が挨拶する(idは1オリジン)
 */

(function() {
    //-----------------------------------------------------------------------------
    // Catクラス定義

    var Cat = function(name, message) {
        this.name = name
        this.message = message || 'にゃー'
    }

    // 挨拶用の文字列を返す
    Cat.prototype.greet = function() {
        return this.name + ": " + this.message
    }

    //-----------------------------------------------------------------------------
    // プラグイン本体

    // 猫のリスト
    var cats = [
        new Cat('たま'),
        new Cat('シロ', 'みゃ~'),
        new Cat('クロ', '……')
    ]

    // プラグインコマンドの登録
    var _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand
    Game_Interpreter.prototype.pluginCommand = function (command, args) {
        _Game_Interpreter_pluginCommand.call(this, command, args)
        if (command === 'CatGreet') {
            $gameMessage.add(cats[args - 1].greet())
        }
    }
})()

이렇게 쓰고 싶어요.


캣 등급을 다른 파일로 나눠서 ES2015 기능을 쓰면 아래처럼 쓸 수 있어 행복하다.
아니, 사실 이런 분량은 결코 행복하지는 않지만, 행복한 미래와 밀접하게 연결된 것 같다.
CatGreetingPlugin.js
コメント部分省略
import Cat from './Cat'

// 猫のリスト
const cats = [
    new Cat('たま'),
    new Cat('シロ', 'みゃ~'),
    new Cat('クロ', '……')
]

// プラグインコマンドの登録
const _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand
Game_Interpreter.prototype.pluginCommand = (command, args) => {
    _Game_Interpreter_pluginCommand.call(this, command, args)
    if (command === 'CatGreet') {
        $gameMessage.add(cats[args - 1].greet())
    }
}

Cat.js
export default class Cat {
    constructor(name, message = 'にゃー') {
        this.name = name
        this.message = message
    }

    // 挨拶を文字列で返す
    greet() {
        return `${this.name}: ${this.message}`
    }
}

구축 환경 만들기


여기서부터 도구를 넣고 cool 뮤직비디오에서 터치한 디렉터리는 통상적인 상태를 유지하며 그 중 한 외부에 다양한 물건을 배치한다.
먼저 캣-greeting이라는 목록을 만들고 그 중에서 mv라는 이름으로 tsuco 뮤직비디오를 만드는 프로젝트입니다.(기존 이름 바꾸기를 이동해도 괜찮습니다. 가능합니다.)
cat-greeting/src/CatGreeting Plugin이라는 디렉터리를 만듭니다. 아까의Cat입니다.js 및 CatGreeting Plugin가입하다
명령 알림이나 파워셸을 시작하고cat-greeting 디렉터리에서 다음 명령을 실행합니다.2
npm init -y
npm i -D babel-core babel-loader babel-preset-es2015 webpack
웹 패키지의 설정 파일을 씁니다.
webpack.config.js
/*
 * src以下のディレクトリがそれぞれプラグインにあたるものとしてビルドする
 * 各ディレクトリの下にある同名のファイルをエントリーポイントとする
 * 例)
 * src
 * ├ HogePlugin
 * │ ├ HogePlugin.js
 * │ └(HogePluginからimportされるファイルなど)
 * └ HugaPlugin
 *   ├ HugaPlugin.js
 *   └(HugaPluginからimportされるファイルなど)
 */
const fs = require("fs");
const inputPath = __dirname + "/src/";
const outputPath = __dirname + "/mv/js/plugins/";

const entries = {};
const fileNames = fs.readdirSync(inputPath);
fileNames.forEach(function(name) {
  const path = inputPath + name;
  if(fs.statSync(path).isDirectory()) {
    entries[name] = path + "/" + name;
  }
});

module.exports = {
  entry: entries,
  output: {
    path: outputPath,
    filename: '[name].js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      }
    ],
  },
  resolve: {
    extensions: ['', '.js']
  }
}
웹 패키지를 간단하게 실행할 수 있도록 미리 해 두다.
package.json(차분)
   "scripts": {
-     "test": "echo \"Error: no test specified\" && exit 1"
+     "build": "webpack"
   },
여기까지의 카탈로그 구성은 이런 느낌이에요.
cat-greeting
├ mv
│ ├ Game.rpgproject
│ └ (その他、いつものMVのやつ)
├ node_modules
│ └ (略)
├ src
│ └ CatGreetingPlugin
│  ├ Cat.js
│  └ CatGreetingPlugin.js
├ package.json
└ webpack.config.js
오다
npm run build
cat-greeting/mv/js/plugins/CatGreetingPlugin.js를 확인한 후 늘 뒤죽박죽이지만 두 파일을 포함하는 내용을 알 수 있을 것 같다.
뮤직비디오 메뉴에서 시연을 해보면 시작과 같은 동작을 확인할 수 있다.완성

과제.


최종적으로 완성된 js 파일은 기계적인 변환을 거쳤기 때문에 읽기가 매우 어렵다.원래 개량 등은 변환 전 원본 파일에서만 하면 되기 때문에 문제가 되지 않고 미니피(Minify)로도 가능하지만, cool) 플러그인으로 나눠주면 사용자가 개조하려는 경우도 있어 문제다.
연관은 있지만 플러그인 리뷰는 중간에 묻힌다.cool MV의 플러그인 관리를 보면 인식은 되지만 설명과 도움말에는 무용지물*(태그가 삽입된 게 문제인가)가 표시됩니다.
두 번째로 플러그인 메모 개선 및 Mocha ESLit ESDoc 활용
엄밀히 말하면 자바스크립트에는 클래스가 존재하지 않기 때문에 클래스처럼 처리할 수 있는 대상이다. 
참고로 자원 관리자의 주소 표시줄에 cmd와 Powerrshell을 치면 이 디렉터리는 현재 디렉터리로 열 수 있어 편리합니다. 

좋은 웹페이지 즐겨찾기