I’m busy learning TypeScript with the goal of writing cleaner and more maintainable frontend code. In this post I’ll show you how to setup an easy build process with Laravel.

First off, you’ll need to run npm install -g typescript. This will give you access to the tsc command. Then you can run laravel new <projectname>.

cd into your newly created project and run tsc --init. This will generate your tsconfig.json file. This file indicates that you’re using TypeScript and allows you to add compiler options needed by the project. You can find more information here.

My tsconfig.js file looks like this:

{
  "compilerOptions": {
    "target": "ES2015",
    "module": "es2015",
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "removeComments": true,
  },
  "include": [
    "resources/assets/ts/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

It’s fairly basic for now, but there are a tonne of options available to you.

Next, you should run the following npm install ts-loader typescript --save-dev. I’ve found that installing TypeScript inside the project itself, just reduces any possible hassles.

Now it’s time to open up your webpack.mix.js and throw the following in there:

mix.webpackConfig({
    resolve: {
        extensions: ['.ts']
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                loader: 'ts-loader'
            }
        ]
    }
});

This gives TypeScript files meaning to Laravel Mix. From here on out it’s business as usual when compiling assets. Just remember to use mix.js and not mix.scripts. The latter only concatenates and minifies JavaScript files.

Example:

mix.js('resources/assets/ts/app.ts', 'public/js').version();

I’ve read about mix.ts being available for TypeScript compiling, but for some reason it would complain about issues that don’t exist. I prefer the path of least resistance so I didn’t go too much into whatever the problem was.

Stay safe.