To use Typescript with spatie/typescript-transformer in an existing Laravel/Inertia/Vue project, you can follow these steps:
- Install the required packages:
npm install --save-dev typescript ts-loader spatie/typescript-transformer
- Create a
tsconfig.jsonfile in the root of your project with the following content:
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"experimentalDecorators": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"isolatedModules": true,
"resolveJsonModule": true,
"noImplicitAny": false,
"noImplicitThis": false,
"noImplicitReturns": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"allowSyntheticDefaultImports": true,
"lib": ["esnext", "dom"]
},
"include": [
"resources/js/**/*"
],
"exclude": [
"node_modules",
"vendor"
],
"plugins": [
{
"transform": "spatie-typescript-transformer"
}
]
}
- Update your
webpack.mix.jsfile to include the Typescript loader:
const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
.vue()
.webpackConfig({
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: { appendTsSuffixTo: [/\.vue$/] },
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['*', '.js', '.jsx', '.vue', '.ts', '.tsx'],
},
});
- Create a
typesdirectory in yourresources/jsdirectory and add your Typescript interfaces and types there. For example, create aDepartment.tsfile with the following content:
export interface Department {
id: number;
code: string;
}
- Use your Typescript interfaces and types in your Vue components. For example, in your
MyComponent.vuefile:
<template>
<div>
<p>Department ID: {{ department.id }}</p>
<p>Department Code: {{ department.code }}</p>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { Department } from '@/types/Department';
export default defineComponent({
props: {
department: {
type: Object as () => Department,
required: true,
},
},
});
</script>
Note: Make sure to update the import path in the MyComponent.vue file to match the location of your Department.ts file.
Reference: https://github.com/spatie/typescript-transformer#usage-with-laravel-mix-and-vuejs