Jump to content
  • Advertisement
  • entries
  • comments
  • views

BabylonJS. Usage TS in Browser



If you what to use a few TypeScript files the Browser you need to bundle them in on file. What is simple and cheap way to make it? Use Browserify + UglifyJS tools.

BabylonJS is a game engine for creating 3D browser games. BJS was written in TypeScript. I this instruction I will show you how to create an example with a few TypeScript files. I do not like use: Webpack, Gulp, Grunt and so on at the beginning for simple examples. Because they require a lot of disk space on my laptop for my little examples. I create a lot of examples when I study something. For example, Gulp requires 80 MB. If I have 100 examples in TS then I will lost 800 MB. I use Browserify for creating a bundle that I can use in the browser. And I use UglifyJS to minify this bundle. You can install them only once using this commands:

npm install browserify -g
npm install uglify-js -g

Generate the “package.json” file using this command:

npm init -y

For example, you have two files with names “Program.ts” and “Game.ts” in the "src" folder. Open the “package.json” file and add these lines in the “scripts” section:

"scripts": {
    "browserify": "browserify dist/Program.js -o dist/bundle.js",
    "uglifyjs": "uglifyjs dist/bundle.js -o dist/bundle.min.js",
    "build": "tsc && npm run browserify && npm run uglifyjs"

You can generate the “bundle.min.js” in the "dist" folder later using this command:

npm run build

You can read here in the documentation: https://doc.babylonjs.com/ this information:



The example project below uses the most recent release of BabylonJS via the BabylonJS CDN, so you don’t need to download BabylonJS locally in order to use it.

However, you will need to download the BabylonJS TypeScript definition file from https://preview.babylonjs.com/babylon.d.ts in order to compile your project. Save this babylon.d.ts file into your project folder and create an empty index.html like so:


I want to keep all “.d.ts” files in the separate folder with the name “typings”. Create a "tsconfig.json" file in your root folder and add this line of code to the “tsconfig.json” folder:

"types": [

You need to add two “script” tags to the “index.html”:

<script src="https://preview.babylonjs.com/babylon.js"></script>
<script src="dist/bundle.min.js"></script>

I will show the “Program.ts” file. Another part of the example you will find here: https://doc.babylonjs.com/ Scroll down and click on the "TypeScript" button.

Source code: official-example-bjs-ts.zip


import { Game } from "./Game";

class Program
    public static Main()
        // Create the game using the 'renderCanvas'.
        let game = new Game('renderCanvas');

        // Create the scene.

        // Start render loop.

window.onload = () =>



Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement
  • Advertisement
  • What is your GameDev Story?

    In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

    (You must login to your GameDev.net account.)

  • Blog Entries

  • Similar Content

    • By chell
      I am currently in school for Game Development and for an assignment I have to make a prototype that showcases my writing skills. I am developing a choice based Twine game as my prototype but I have a few questions. The basic premise is focusing on the emotional consequences and traumas of fighting in a mech during war time.

      How long should the prototype be in order to showcase my writing skills?

      Should I include any limited art? I am not good at developing 2D art assets and I'm worried that adding some might detract from writing. 
    • By KPK
      Hello! I am a bit new to this, so pardon my etiquette. I am a student who is currently learning the basics of programming with C++ and I intend on expanding my knowledge further outside what my classes will be teaching me as I make my way towards an Engineering degree. I would like to throw my hat in on my spare time to learn to program 2D games that are based in C++, but I do not know where exactly to start doing so, particularly in the area of what software I need and can get to turn the limited black-background-white-text output from "Windows Visual Studio 2017" to generating the images/menus/sounds/visuals/controller-input needed to at least have the basic tools required to make a game.
      So, long story short: what software do I need to start programming a video game? Where can I get it? Any advice, tutorial links, or input would be much appreciated! Thanks!
    • By Berend Salverda
      Hey all I'm an aspiring composer and would love to work on videogame projects. What do you think, would this music work, is this something you'd use?
      Love to hear your opinions!
      Kind Regards,
    • By lolanto lu
      I'm new to DirectX12. I've read document about DirectX12 for some days and now I just want to use it to draw a triangle. But it's not work! I used PIX to debug the program and I found that my pixel shader has no output!. I don't know if there's something wrong with my Pipeline State Object settings.
      this is the function that create the PSO
      /** vs and ps are indices of shader resource which have been compiled with dxc.exe in sm6 and stored in a map called shaders */ void Renderer::CreatePSO(uint32_t vs, uint32_t ps) { D3D12_INPUT_LAYOUT_DESC inputDesc; D3D12_INPUT_ELEMENT_DESC pos; pos.SemanticName = "POSITION"; pos.SemanticIndex = 0; pos.Format = DXGI_FORMAT_R32G32B32_FLOAT; pos.InputSlot = 0; pos.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA; pos.AlignedByteOffset = D3D12_APPEND_ALIGNED_ELEMENT; pos.InstanceDataStepRate = 0; inputDesc.NumElements = 1; inputDesc.pInputElementDescs = &pos; D3D12_RASTERIZER_DESC rasterDesc = {}; /**< use default value */ rasterDesc.FillMode = D3D12_FILL_MODE_SOLID; rasterDesc.CullMode = D3D12_CULL_MODE_NONE; /**< disable cull */ rasterDesc.DepthClipEnable = false; D3D12_GRAPHICS_PIPELINE_STATE_DESC desc = {}; desc.pRootSignature = mRootSignature.Get(); ID3DBlob* const vsb = shaders[vs].Get(); ID3DBlob* const psb = shaders[ps].Get(); desc.VS.BytecodeLength = vsb->GetBufferSize(); desc.VS.pShaderBytecode = vsb->GetBufferPointer(); desc.PS.BytecodeLength = psb->GetBufferSize(); desc.PS.pShaderBytecode = psb->GetBufferPointer(); desc.StreamOutput = {}; desc.BlendState = {}; desc.InputLayout = inputDesc; desc.SampleMask = 0; desc.RasterizerState = rasterDesc; desc.DepthStencilState = {}; /**< use the default value */ desc.DepthStencilState.DepthEnable = false; /**< disable depth testing */ desc.DepthStencilState.StencilEnable = false; /**< disable stencil testing */ desc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; desc.NumRenderTargets = 1; desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; desc.DSVFormat = DXGI_FORMAT_UNKNOWN; /**< since there is no depth stencil buffer */ desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.NodeMask = 0; desc.CachedPSO = {}; desc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; if (FAILED(mDevice->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&mPSO)))) throw("create pipeline state failed"); } And this is the function that setting command list for each frame
      void Renderer::Run() { WindowBase::MainLoop = [this](float) { /** Command List setting for each frame */ mCmdList->Reset(mCmdAloc.Get(), nullptr); mCmdList->SetPipelineState(mPSO.Get()); /**< Which is created throgh Function CreatePSO */ /** A constant buffer in the heap that I never use within my shaders */ D3D12_GPU_DESCRIPTOR_HANDLE gpuHandle = mBufDescHeap->GetGPUDescriptorHandleForHeapStart(); ID3D12DescriptorHeap* heaps[] = { mBufDescHeap.Get() }; mCmdList->SetDescriptorHeaps(1, heaps); mCmdList->SetGraphicsRootSignature(mRootSignature.Get()); mCmdList->SetGraphicsRootDescriptorTable(0, gpuHandle); /** Vertex And Index Buffers setting */ mCmdList->IASetVertexBuffers(0, 1, &mVtxBufView); mCmdList->IASetIndexBuffer(&mIdxBufView); mCmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); /** Viewport and Scissor Rect settings. mWidth = 300 and mHeight = 300. */ D3D12_VIEWPORT viewport = {}; viewport.Height = mHeight; viewport.Width = mWidth; viewport.MaxDepth = 1.0f; viewport.MinDepth = 0.0f; viewport.TopLeftX = 0; viewport.TopLeftY = 0; mCmdList->RSSetViewports(1, &viewport); D3D12_RECT scissorRect; scissorRect.bottom = mHeight; scissorRect.right = mWidth; scissorRect.top = scissorRect.left = 0; mCmdList->RSSetScissorRects(1, &scissorRect); D3D12_RESOURCE_BARRIER barrier; barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; barrier.Transition.pResource = mRtvs[mSwapChain->GetCurrentBackBufferIndex()].Get(); barrier.Transition.Subresource = 0; barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT; barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; mCmdList->ResourceBarrier(1, &barrier); D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = mRtvDescHeap->GetCPUDescriptorHandleForHeapStart(); rtvHandle.ptr += mRtvDescHeapSize * mSwapChain->GetCurrentBackBufferIndex(); static float clearColor[] = { 0.2f, 0.4f, 0.6f, 1.0f }; mCmdList->ClearRenderTargetView(rtvHandle, clearColor, 0, nullptr); /** no depth stencil buffer here, since i don't want to use depth testing */ mCmdList->OMSetRenderTargets(1, &rtvHandle, false, nullptr); mCmdList->DrawIndexedInstanced(3, 1, 0, 0, 0); barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT; mCmdList->ResourceBarrier(1, &barrier); mCmdList->Close(); ID3D12CommandList* list[] = { mCmdList.Get() }; mCmdQue->ExecuteCommandLists(1, list); mSwapChain->Present(1, 0); /** Waiting until above commands were executed */ synchronizationCPU(mCmdQue.Get(), mFence.Get(), mNextFenceValue, mFenceEventHandle); }; win->Run(); /** start window's main loop */ } And here is my simplest vertex shader and pixel shader(I used dxc.exe to compile it in Shader Model 6_0)
      ///////////////////////////////// // VERTEX SHADER ///////////////////////////////// float4 main( float3 pos : POSITION ) : SV_POSITION { return float4(pos, 1.0f); } ///////////////////////////////// // PIXEL SHADER ///////////////////////////////// float4 main() : SV_TARGET { return float4(1.0f, 1.0f, 1.0f, 1.0f); } Vertex buffer and Index buffer are also very simple
      std::array<float, 9> VtxData = { -.5f, 0.0f, 0.0f, 0.0f, .5f, 0.0f, .5f, 0.0f, 0.0f }; std::array<uint32_t, 3> IdxData = { 0, 1, 2 };  
      By the way, I have used the debug layer and there is no error or warning message. When I try to use PIX to debug the pixel that should be inside the triangle, it warn me that "Shader Debugging returned no invocation records. Check that your selected pixel, vertex, or thread exists and was executed on this draw call". 
      My Vertex Shader has the correct output which should not be culled anymore

      Hope anybody can give me some suggestions to do more test. Thanks!!! (Seriously, DirectX12 is really harder than DirectX11...)
    • By Javi Raijin
      Hey! I feel spam, but I'm doing a project to draw all the gods of Nordic mythology to make an app that collects all the information about them and then add creatures and heroes.  All the images and the interface will be created by me, unlike the other applications that take images of the internet.
      Any support I would appreciate
      PATREON: https://www.patreon.com/raijinsillustrations
      Odin the god of gods


Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!