现已成功引入了webpack,运行npm start启动项目,会自动打开chrome浏览器,我们看到游戏已经跑起来了!尝试修改src/js/main.js文件,保存下,页面会自动刷新,我们的修改也已经能反映到页面上了!
构建项目
运行git checkout master切换到master分支即可看到这最终一步的示例。
引入babel让你能使用最新的ES特性(这些库主要是为了ES6+转ES5,还有些pollyfill等等,这里不做过多的解释,具体可参考babel官方文档)。
npm install --save-dev @babel/core @babel/plugin-transform-runtime @babel/preset-env babel-loader
npm install --save core-js @babel/runtime
引入gulp,运行npm install --save-dev gulp gulp-if gulp-imagemin rimraf安装依赖。
创建gulpfile.js
const { src, dest, parallel } = require('gulp') const path = require('path') const gulpif = require('gulp-if') const imagemin = require('gulp-imagemin') const webpack = require('webpack') const webpack_config = require('./webpack.prod') function copyAssets() { return src(['src/**/*', '!src/js/**']) .pipe(gulpif( file => path.extname(file.relative) === '.png', imagemin([imagemin.optipng({ optimizationLevel: 3 })], { verbose: true }))) .pipe(dest('dist')) } function jsBundle(next) { const compiler = webpack(webpack_config) compiler.run((err, stats) => { if (err || stats.hasErrors()) { console.error(stats.toJson().errors) } next() }) } exports.dist = parallel(copyAssets, jsBundle)
在package.json中script节加入构建相关命令,然后run npm build就能成功打包了!
{ "name": "pixi-webpack-demo", "version": "1.0.0", "description": "make pixi.js game with webpack and gulp", "main": "src/js/main.js", "scripts": { "start": "webpack-dev-server --open 'google chrome' --config webpack.dev.js", "clean": "rimraf dist", "prebuild": "npm run clean", "build": "gulp dist" }, "author": "yulijun", "keywords": ["pixi.js","webpack"], "license": "MIT", "devDependencies": { "@babel/core": "^7.8.4", "@babel/plugin-transform-runtime": "^7.8.3", "@babel/preset-env": "^7.8.4", "babel-loader": "^8.0.6", "rimraf": "^3.0.2", "gulp": "^4.0.0", "gulp-if": "^2.0.2", "gulp-imagemin": "^4.1.0", "webpack": "^4.41.5", "webpack-cli": "^3.3.10", "webpack-dev-server": "^3.10.3", "webpack-merge": "^4.2.2" }, "dependencies": { "@babel/runtime": "^7.8.4", "core-js": "^3.6.4", "pixi.js": "^5.2.1" } }
恭喜你,至此开发和构建环境已经全部完成,可尝试在源码中添加一些es6+语法,然后运行npm run build构建项目,最终打包好的项目会在dist目录中,js已经被混淆并合并为game.min.js,无用的引用通过tree shake已经被去掉了,包尺寸优化到了最小,而且所有es6+的语法均转换为es5以适应更多的浏览器。所有的图片也都进行了压缩处理。