Home > PHP Framework > Laravel > body text

A brief analysis of how to use Typescript in Laravel

青灯夜游
Release: 2022-12-27 20:21:41
forward
1302 people have browsed it

How to use Typescript in Laravel? The following article will introduce to you how to use Typescript in Laravel. I hope it will be helpful to you!

A brief analysis of how to use Typescript in Laravel

More and more PHP and more specifically Laravel developers have started writing more strongly typed code, while full stack developers tend not to type the same Practices applied to their front-end code. Among them, TypeScript is considered a "different" way to write front-end components. [Related recommendations: laravel video tutorial]

Most misunderstandings about TypeScript are that it is too complex for back-end developers and will only expand the code size without any Provide any additional value.

Actually, TypeScript does not force you to declare types. This is the important part: TypeScript is a superset of JavaScript that lets you add stuff on top of it, but any valid JS is also valid TS.

The practical impact of this is that you can rename the file from .js to .ts and gradually add types or start using types in the new file . Your codebase doesn't have to have 100% type coverage. You can use TypeScript according to your choice.

Why use TypeScript

TypeScript provides optional static typing, which allows you to build and verify your code during the compilation phase. It also brings IDE auto-completion and validation support and code navigation capabilities. In short, TypeScript enhances code readability and improves the debugging process.

Adding TypeScript support to your Laravel project is easy, takes only a few minutes, but can improve your front-end experience. Let’s review the process by reinstalling Laravel Breeze with Vue 3.

1. Install dependencies

Let’s start by installing the TypeScript compiler and the corresponding Webpack loader.

npm install ts-loader typescript --save-dev
# 或者
yarn add ts-loader typescript -D
Copy after login

2. Set up TypeScript configuration

The TypeScript compiler requires a configuration file that contains the required options. Appropriate IDE autocompletion is also desirable.

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "es2020",
    "moduleResolution": "node",
    "baseUrl": "./",
    "strict": true,                 // Enable strict type-checking options
    "skipLibCheck": true,           // Skip type checking of declaration files
    "noImplicitAny": false          // Bypass raising errors on `any` type
  },
  "include": ["resources/js/**/*"]  // 前端路径模式
}
Copy after login

3. Configuring Laravel Mix

The initial Laravel installation comes with An example of a JavaScript entry that needs to be converted to TypeScript. You just need to rename .js to .ts.

-resources/js/app.js
+resources/js/app.ts
Copy after login

Then, let Mix know that it should handle the JavaScript code as TypeScript. Laravel Mix comes with built-in TypeScript support.

webpack.mix.js

-mix.js('resources/js/app.js', 'public/js')
+mix.ts('resources/js/app.ts', 'public/js')
Copy after login

You also need to tell the compiler and IDE that the component's code must be treated as TypeScript. Append the lang="ts" section to the component script section.

<script lang="ts">
import { defineComponent } from "@vue/runtime-core";

export default defineComponent({
    ...
});
</script>
Copy after login

Are you ready? You can continue writing code the same way you did before and take advantage of some TypeScript features and improve your front-end experience.

Example Usage

TypeScript allows you to type-hint variables and methods using simple types and complex structures. Since we are mainly focused on interacting with the backend, let's look at an example of interacting with the model.

Let's create a file containing all necessary type declarations - resources/js/types.d.ts.

Suppose you have a model user that you can interact with from the front end. This is a basic TypeScript representation of the default user model. It describes what properties an object can have and what type those properties should be.

resources/js/types.d.js

declare interface User {
    id: number;
    name: string;
    email: string;
}
Copy after login

Now you can use this interface when assigning variables or returning values ​​from methods .

let user = <User>{ id: 1, name: &#39;Taylor Otwell&#39; }

function getUser(): User {
    ...
}
Copy after login

So when you access a user variable, your IDE will suggest the corresponding object properties. It also lets you know when a type error occurs before you compile your code.

Writing interfaces for all models and keeping them in sync with the backend code requires additional time. You may want to consider using the laravel-typescript extension, which allows you to convert Laravel models into TypeScript declarations and keep them in sync with your migrations.

Original address: https://laravel-news.com/typescript-laravel

Translation address: https://learnku.com/laravel/t/67586

For more programming related knowledge, please visit: Programming Video! !

The above is the detailed content of A brief analysis of how to use Typescript in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template