How to use typescript in browser?

后端 未结 4 461
無奈伤痛
無奈伤痛 2020-12-31 04:21

utility.ts

let books = [
    { id: 1, title: \"the dark window\", author: \"krishna\", available: true },
    { id: 2, title: \"naked eye\", author: \"sydney         


        
相关标签:
4条回答
  • 2020-12-31 05:04

    Im new to AMD but it looks like you only define the modules, never invoke/import them to the sites scope. In this tutorial the author has a bootstrapping file that acts as entry point for an app which seems to be what you're missing: http://www.codebelt.com/typescript/typescript-amd-with-requirejs-tutorial/

    0 讨论(0)
  • 2020-12-31 05:16

    Browsers do not yet support javascript modules. Until they do you will need to include browserify into your development workflow. Browserify concatenates your modules into a browser friendly bundle.

    Browserify is very simple to get working in a typescript workflow. If you are feeling adventurous you can look at other bundlers like WebPack, Rollup or SystemJs.

    Note, this is not specific to TypeScript. When developing any modern javascript (es6 or CommonJS modukes) you will need to bundle modules for the browser.

    0 讨论(0)
  • 2020-12-31 05:16

    I think the title is incorrect and what you really trying to do is running TypeScript applications in te browser which is totally different yo "Run TypeScript in the browser, right?

    In that case to get started with TypeScript I recommend you to not use require.js add instead a bundler-like tool like a tool like parcel, webpack, browserify, rollup. parcel is super easy : For your example, 1) remove ALL script tags and add only the following: <script src="my/app.ts"> then "compile" that html with parcel theFile.html or build for production : parcel build theFile.html

    if I was right, could you please change the title of this question since is confusing and misleading ? thanks.

    Now, on the other side, If you really want to run TypeScript as the title say, typescript is fully compatible with the browser (the .js file library is node_modules/typescript/lib/typescript.js ). just import it as another module or load the file in a script tag and use the Compiler API..

    This project contains my research on the topic with several working examples and demo apps and some tools: https://github.com/cancerberoSgx/typescript-in-the-browser

    0 讨论(0)
  • 2020-12-31 05:18
    1. Update browser to recent one (recent enough to support ES2015 module)
    2. Change tsconfig.json target to es2015
    3. Change tsconfig.json module to es2015
    4. Always add .js extension to your import statements
    5. Use an http server like live-server to avoir CORS concerns with file:// protocol

    BONUS: Explicitly set tsconfig.json moduleResolution to node. This is not necessary if you don’t use external libraries or @types/* packages.

    See it altogether at : https://github.com/SalathielGenese/ts-web

    Disclosure : I'm its author.

    0 讨论(0)
提交回复
热议问题