1. The background
Normally we debug and develop our projects under the LayaAir IDE. You don’t usually get to see typescript “compile” and bundle processes. In this section we are going to take a closer look at the process and break it down to be able to run projects directly in VsCode and compile and debug them in real time.
2. Compilation process of LayaAir
Open the LayaAirIDE folder
LayaAirIDE_beta\resources\app\out\vs\layaEditor\laya\code\ts\empty
Copy the code
This set of templates is used when we create empty projects, and when we compile directly in the IDE, we use the NODE environment and plug-ins that come with the IDE. Gulp and rollup are used to compile the file in.laya/compile.js.
V1.2.5 // Whether to use the IDE node environment and plug-ins, set false, Const useIDENode = process.argv[0].indexof ("LayaAir") > -1? true : false; const useCMDNode = process.argv[1].indexOf("layaair2-cmd") > -1 ? true : false; function useOtherNode(){ return useIDENode||useCMDNode; } let ideModuleDir = useOtherNode()? process.argv[1].replace("gulp\\bin\\gulp.js", "").replace("gulp/bin/gulp.js", "") : ""; let workSpaceDir = useOtherNode() ? process.argv[2].replace("--gulpfile=", "").replace("\\.laya\\compile.js", "").replace("/.laya/compile.js", "") : "./.. / "; const gulp = require(ideModuleDir + "gulp"); const rollup = require(ideModuleDir + "rollup"); const typescript = require(ideModuleDir + 'rollup-plugin-typescript2'); //typescript2 plugin const glsl = require(ideModuleDir + 'rollup-plugin-glsl'); const path = require('path'); const fs = require('fs'); // If the compile function is called, add prevTasks let prevTasks = ""; if (global.publish) { prevTasks = ["loadConfig"]; } gulp.task("compile", prevTasks, function () { If (global.publish) {workSpaceDir = global.workspacedir; WorkSpaceDir uses the publish.js variable let forceCompile =! fs.existsSync(path.join(workSpaceDir, "bin", "js", "bundle.js")); // If (! global.config.compile && ! forceCompile) { return; } } return rollup.rollup({ input: workSpaceDir + '/src/Main.ts', onwarn:(waring,warn)=>{ if(waring.code == "CIRCULAR_DEPENDENCY"){ console.log("warnning Circular dependency:"); console.log(waring); }}, treeshake: false, // Ignore plugins: [typescript({tsconfig:workSpaceDir + "/tsconfig.json", check: true, //Set to false to avoid doing any diagnostic checks on the code tsconfigOverride:{compilerOptions:{removeComments: true}}, include:/.*.ts/, }), glsl({ // By default, everything gets included include: /.*(.glsl|.vs|.fs)$/, sourceMap: false, compress:false }), /*terser({ output: { }, numWorkers:1,//Amount of workers to spawn. Defaults to the number of CPUs minus 1 sourcemap: false })*/ ] }).then(bundle => { return bundle.write({ file: workSpaceDir + '/bin/js/bundle.js', format: 'iife', name: 'laya', sourcemap: false }); }).catch(err=>{ console.log(err); })});Copy the code
Open.vscode/launch.json to see that you are using the Debugger for Chrome plugin
{" version ":" 0.2.0, "" configurations: [{" name" : "chrome debug", "type" : "chrome", "request" : "launch", "file" : "${workspaceRoot}/bin/index.html", // "Replace your own Google installation path, ": for example //window default installation path is: "C: / Program Files (x86)/Google/Chrome/Application/Chrome. Exe" / / MAC on the system default installation path is/Applications/Google. Chrome.app/Contents/MacOS/Google Chrome"; // "runtimeExecutable": "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", "runtimeArgs": [ "--allow-file-access-from-files", " --disable-web-security" ], "sourceMaps": true, "webRoot": "${workspaceRoot}", // If the Google debug message userDataDir is not available, please make the Google installation path administrator permissions, or replace ${tmpdir} with another readable and writable folder, or delete it. "${workspaceRoot}/.laya/chrome", "sourceMapPathOverrides": { "src/*": "${workspaceRoot}/src/*" } } ] }Copy the code
3. Gulp real-time compilation and stripping
In the traditional laya project development process, it is common to change the code, click Chorme in the IDE to compile, and then wait some time before opening the browser for debugging. This process can be further optimized by updating the Watch code to recompile in time and refresh the browser.
3.1 Launch and Task configuration
{" version ":" 0.2.0, "" configurations: [{" name" : "chrome debug", "type" : "chrome", "request" : "launch", "trace" : true, "smartStep": true, "file": "${workspaceRoot}/bin/index.html", "runtimeArgs": [ "--allow-file-access-from-files", "--allow-file-access-frome-files", "--disable-web-security" ], "sourceMaps": true, "webRoot": "${workspaceRoot}", "userDataDir": "${workspaceRoot}/.vscode/chrome", "fixedPort":false, "sourceMapPathOverrides": { "src/*": "${workspaceRoot} / SRC / *"}, "preLaunchTask" : "gulp"}, {" name ":" chrome confusion ", "type" : "chrome", "request" : "launch", "trace": true, "smartStep": true, "file": "${workspaceRoot}/bin/index.html", "runtimeArgs": [ "--allow-file-access-from-files", "--allow-file-access-frome-files", "--disable-web-security" ], "sourceMaps": true, "webRoot": "${workspaceRoot}", "userDataDir": "${workspaceRoot}/.vscode/chrome", "fixedPort":false, "sourceMapPathOverrides": { "src/*": "${workspaceRoot} / SRC / *"}, "preLaunchTask" : "uglify"}, {" name ":" real-time compilation ", "request" : "launch", "type" : "pwa-chrome", "trace": true, "smartStep": true, "url": "http://localhost:1688", "runtimeArgs": [ "--allow-file-access-from-files", "--allow-file-access-frome-files", "--disable-web-security" ], "sourceMaps": true, "webRoot": "${workspaceFolder}/bin", "sourceMapPathOverrides": { "src/*": "${workspaceRoot}/src/*" }, }, ] }Copy the code
task.json
{" version ":" 2.0.0 ", "tasks" : [{" label ":" gulp ", "type" : "shell", "command" : "gulp", "group" : {" kind ": "build", "isDefault": true } }, { "label": "uglify", "type": "shell", "command": "gulp uglify", "group": { "kind": "build", "isDefault": true } }, { "label": "watch", "type": "shell", "command": "gulp watch", "group": { "kind": "build", "isDefault": true } }, ] }Copy the code
3.2 gulpfile
Install gulp and the required libraries in the project folder
Var gulp = require("gulp"); var browserify = require("browserify"); var source = require("vinyl-source-stream"); var sourcemaps = require('gulp-sourcemaps'); var buffer = require('vinyl-buffer'); var tsify = require("tsify"); let uglify = require('gulp-uglify-es').default; const watchify = require("watchify"); const gutil = require("gulp-util"); const connect = require('gulp-connect'); / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- real-time compile -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- const watchedBrowserify = watchify (browserify ({ debug: true, entries: ['src/Main.ts'], cache: {}, packageCache: {} }).plugin(tsify)); Function browserifyBundle() {return watchedBrowserify.bundle () // Use source to name the output file bundle.js.pipe (source('bundle.js')) .pipe(buffer()) .pipe(sourcemaps.init({ loadMaps: Pipe (gulp.dest("bin/js")).pipe(connect.reload()); // Copy bundle.js to bin/js. Gulp.task ('connect', function () {connect.server({root: "./bin", livereload: true, port: 1688}); }); gulp.task("browserify", function() { return browserifyBundle(); }) gulp.task("watch", gulp.series('browserify', 'connect')); watchedBrowserify.on("update", browserifyBundle); watchedBrowserify.on("log", gutil.log); / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - the default compiler -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / use browserify, convert ts to js, Gulp.task ("default", function () {return browserify({// whether to enable debugging, jSmap will be generated, easy to debug ts source code, but will impact the compilation speed. true, entries: ['src/Main.ts'], cache: {}, packageCache: Plugin.tsify (tsify).bundle() // Use source to name the output file bundle.js.pipe (source('bundle.js')).pipe(buffer()). .pipe(sourcemaps.init({ loadMaps: Pipe (sourcemaps.write('./')) // Copy bundle.js to bin/js directory. Pipe (gulp.dest("bin/js")); }); Gulp.task ("uglify", function () {return browserify({// whether to enable debugging, jsmap will be generated, easy to debug ts source code, but will impact the compile speed ['src/Main.ts'], cache: {}, packageCache: Plugin.tsify (tsify).bundle() // Use source to name the output file bundle.js.pipe (source('bundle.js')).pipe(buffer()). .pipe(sourcemaps.init({ loadMaps: true })) .pipe(uglify({mangle: False})).pipe(sourcemaps.write('./')) // Copy bundle.js to bin/js directory.pipe(gulp.dest("bin/js")); });Copy the code
To use gulp Watch, first execute gulp Watch in the project folder and then click Live Compile