webpack 新建 phaser3 的 h5 项目简单模板

一、新建项目

1. 项目文件夹

在本地合适位置新建项目文件夹,用以存放项目代码

2. 项目目录结构

新建项目结构如下

- 根目录
	- src
		- assets
		- scene
		- sprite
		- util
		- config
	- webpack

其中

  • src:用于存放项目代码
    • assets:项目资源,如图片,声音等
    • scene:phaser3 的场景类
    • sprite:phaser3 的 sprite 类
    • util:工具类
    • config:用于存放项目配置文件的目录
  • webpack:webpack 的相应配置文件目录(也可以自定义其他的目录和其他配置)

二、项目初始化

打开终端,在项目根目录下运行如下命令,并根据提示逐步输入信息(可以一路回车默认)

$ sudo npm init

如果之前没全局安装过webpack,就先安装一下

$ npm install webpack -g

根目录下出现 package.json 文件,并且信息正确,初始化成功


三、添加依赖

在 package.json 中添加项目需要的依赖如

"devDependencies": {
  "@azerion/phaser-spine": "^3.0.9",
  "@babel/core": "^7.2.2",
  "@babel/preset-env": "^7.2.3",
  "babel-loader": "^8.0.5",
  "clean-webpack-plugin": "^1.0.0",
  "css-loader": "^3.0.0",
  "file-loader": "^3.0.1",
  "html-webpack-plugin": "^3.2.0",
  "less": "^3.9.0",
  "less-loader": "^5.0.0",
  "raw-loader": "^1.0.0",
  "style-loader": "^0.23.1",
  "terser-webpack-plugin": "^1.2.1",
  "webpack": "^4.28.3",
  "webpack-cli": "^3.2.1",
  "webpack-dev-server": "^3.1.14",
  "webpack-merge": "^4.2.1"
},
"dependencies": {
  "phaser": "^3.18.1"
}

运行命令,安装依赖

$ sudo npm install

四、项目入口

1. index.html

在项目根目录下新建 index.html,内容如下,其中,id 为 game-area 的 div 是在 phaser 中需要用来铺展画布的区域,id 需要和 phaser 配置中的 paren 对应

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>看我飞刀</title>
</head>
<body>
    <div id="game-area" class="game-area"></div>
</body>
</html>

2. index.less

在 src 目录下新建 index.less,index.less 是 index.html 的样式表如

body {
  margin: 0;
  padding: 0;

  .game-area {
    position: absolute;
    padding: 0;
    margin: 0;
    width: 100%;
    height: 100%;
  }
}

3. index.js

在 src 目录下新建 index.js ,index.js 是入口文件,初始内容如下

import Phaser from 'phaser';
import * as config from './config/gameconf';
import * as SceneUtils from './util/sceneUtils';
import './index.less';

class Game extends Phaser.Game {
    constructor() {
        super(config.initGameConf);
        SceneUtils.changeTo(SceneUtils.scenes.boot, this);
    }
}

window.game = new Game();

4. index.js 是入口,因此需要修改 package.js 的main字段为

"main": "src/index.js",

五、项目其他配置

1. babel 配置

在根目录下新建 .babelrc 文件并给初始化配置,以下配置意思为:支持 ES6+ 的使用并且 Babel 会把它转换为你想要被支持的版本,目标浏览器的配置在 .babelrc 文件中,默认配置支持所有当前的使用率超过0.25%的浏览器,但不包括 IE11 和 Opera Mini

{
  "presets": [
    ["@babel/env", {
      "targets": {
        "browsers": [
          ">0.25%",
          "not ie 11",
          "not op_mini all"
        ]
      },
      "modules": false
    }]
  ],
}

2. 场景切换工具类

在 根目录/src/util 下新建文件 sceneUtils

import Boot from '../scene/Boot';
import Load from '../scene/Load';
import Menu from '../scene/Menu';
import Play from '../scene/Play';
import End from '../scene/End';

/**
 * 初始化场景
 * @type {boolean} 是否被初始化过
 * @param context 上下文
 */
let isInit = false;
const initScene = context => {
    context.scene.add(scenes.boot, Boot);
    context.scene.add(scenes.load, Load);
    context.scene.add(scenes.menu, Menu);
    context.scene.add(scenes.play, Play);
    context.scene.add(scenes.end, End);
    isInit = true;
};

/**
 * <p>当前所有场景在此处注册
 *
 * <p>分别为
 * <code>
 *     {
 *         boot: 初始场景,为第一个场景,用来做一些设置,比如设置scaleMode或者居中等,
 *         loading: 第二个场景,用来加载资源
 *         menu: 游戏开始菜单界面,
 *         play: 游戏主界面,
 *         end: 结束界面
 *     }
 * </code>
 */
export const scenes = {
    boot: 'Boot', load: 'Load', menu: 'Menu', play: 'Play', end: 'End'
};

/**
 * 切换场景方法,传入场景值即可切换
 * @param targetScene 需要转换的目标场景
 * @param context 上下文
 */
export const changeTo = (targetScene, context) => {
    if (!isInit) {
        initScene(context);
    }
    context.scene.start(targetScene);
};


3. 游戏配置

在 根目录/src/config 下新建 gameconf.js 文件

import Phaser from "phaser";

export const initGameConf = {
    mode: Phaser.Scale.FIT,
    autoCenter: Phaser.Scale.CENTER_HORIZONTALLY,
    type: Phaser.AUTO,
    width: 750,
    height: 1334,
    parent: 'game-area',
    title: 'FlyKnife',
    localStorageName: 'flyknife',
    webFonts: ['Bangers']
};

/**
 * @type {{
 *  changeTime: number,
 *  maxRotationSpeed: number,
 *  throwSpeed: number,
 *  rotationVariation: number,
 *  rotationSpeed: number,
 *  minAngle: number}}
 *  <p> rotationSpeed: 设置旋转速度,即每一帧转动的角度
 *  <p> throwSpeed: 刀飞出去的速度, 即一秒中内移动像素
 *  <p> minAngle: 两把刀之前的最小角度(约束角度)
 *  <p> rotationVariation: 最大转动的变化量,即每一帧上限
 *  <p> changeTime: 下一秒的变化速度
 *  <p> maxRotationSpeed: 最大旋转速度
 */
export const gameOption = {
    rotationSpeed: 3,
    throwSpeed: 150,
    minAngle: 15,
    rotationVariation: 2,
    changeTime: 2000,
    maxRotationSpeed: 6
};

六、初始化场景

在 根目录/src/scene 下新建 Boot.js,Load.js,Menu.js,Play.js,End.js 等初始化场景如

import Phaser from 'phaser';

export default class Boot extends Phaser.Scene {
    preload() {
        console.log('Boot preload...');
    }

    create() {
        console.log('Boot create...');;
    }

    update() {
        console.log('Boot update...');
    }

    render() {

    }
}


七、项目运行脚本

修改 package.json 文件的 script 字段为

"scripts": {
  "build": "webpack --config webpack/prod.js ",
  "start": "webpack-dev-server --config webpack/base.js --open"
},

然后在项目根目录下新建 webpack 文件夹,并在该文件夹下新建 prod.js 和 base.js 文件

文件初始配置如下,后续如有配置更改的需要,则直接更改此文件夹下配置或新建配置文件和运行脚本即可

// base.js
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");

module.exports = {
  mode: "development",
  devtool: "eval-source-map",
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: [/\.vert$/, /\.frag$/],
        use: "raw-loader"
      },
      {
        test: /\.(gif|png|jpe?g|svg|xml)$/i,
        use: "file-loader"
      },
      {
        test: /\.less$/,
        use: ['style-loader', 'css-loader', 'less-loader']
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(["dist"], {
      root: path.resolve(__dirname, "../")
    }),
    new webpack.DefinePlugin({
      CANVAS_RENDERER: JSON.stringify(true),
      WEBGL_RENDERER: JSON.stringify(true)
    }),
    new HtmlWebpackPlugin({
      template: "./index.html"
    })
  ]
};

// prod.js
const merge = require("webpack-merge");
const path = require("path");
const base = require("./base");
const TerserPlugin = require("terser-webpack-plugin");

module.exports = merge(base, {
  mode: "production",
  output: {
    filename: "bundle.min.js"
  },
  devtool: false,
  performance: {
    maxEntrypointSize: 900000,
    maxAssetSize: 900000
  },
  optimization: {
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          output: {
            comments: false
          }
        }
      })
    ]
  }
});

八、git

1. Github 上新建项目

2. 新建 .gitignore 文件

在本地项目根目录下新建 .gitignore 文件如下

# System and IDE files
Thumbs.db
.DS_Store
.idea
*.suo
*.sublime-project
*.sublime-workspace

# Vendors
node_modules/

# Build
dist/
/npm-debug.log

3. readme 文件

新建 readme 文件初始内容如下

## 命令说明

|命令|描述|
|:---|:----|
|`npm install`|克隆项目后要做的事,即安装所有依赖|
|`npm start`|构建项目并在网页中打开他|
|`npm run build`|根据配置打包项目|

## 模板自定义

### Babel
支持 ES6+ 的使用并且 Babel 会把它转换为你想要被支持的版本,目标浏览器的配置在 `.babelrc` 文件中,
默认配置支持所有当前的使用率超过0.25%的浏览器,但不包括 IE11 和 Opera Mini

### Webpack
如果想要更改 build 方式,比如添加一个 webpack loader 或者 plugin,你可以修改 `webpack/base.js` 文件,或者你也可以另外修改或创建
一个配置文件,并将其作为“package.json”中特定的 npm 任务的目标

### 打包
在你运行 `npm run build` 打包项目后,你的代码将与项目依赖的任何其他 assets 一起构建到位于 `dist/bundle.min.js` 的单个包中,
如果你将 dist 文件夹的内容放在一个可公开访问的位置(比如 `http://mycoolserver.com`),你应该
就能够打开 `http://mycoolserver.com/index.html` 然后开心的玩上游戏?了

4. 推送到git仓库

git init
git add .
git commit -m "init"
git remote add origin git@github.com:codinghck/flyknife.git
// 如果遇到fatal: remote origin already exists.问题,
// 则git remote rm origin后重试
git push -u origin master

八、结果

项目结果的结构如下

- 根目录
	- src
		- assets
		- scene
			- Boot.js
			- Load.js
			- Menu.js
			- Play.js
			- End.js
		- sprite
		- util
			- sceneUtils.js	
			- device.js
		- config
			- gameconf.js
		- index.js
		- index.less
	- webpack
		- base.js
		- prod.js
	- index.html
	- .gitignore
	- .babelrc
	- package.json
	- package-lock.json
	- README.md

至此,phaser3 的 webpack 项目,初始化新建完成

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值