JavaScript has evolved quite a bit from its humble beginnings. Unfortunately, some of those advances have been difficult to take advantage of. Some require features not supported by all browsers, others require complicated tools. For my latest Mojolicious web app, I wanted to see how I could use Typescript with a minimum of fuss.
We'll start from a simple Mojolicious::Lite app, created using mojo generate lite_app
:
From there, we can install Typescript using Node. Since Typescript cannot bundle itself into a single file, we will also install Webpack:
npm install --save-dev typescript webpack webpack-cli ts-loader
After installation we can configure Typescript using its tsconfig.json file. We'll use the public
directory for our output, since this directory is served by Mojolicious.
{
"compilerOptions": {
"outDir": "./public/",
"sourceMap": true,
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true,
"moduleResolution": "node"
}
}
We'll also need to configure Webpack's webpack.config.js
file to get it to bundle everything into a single app.js
file we can use. We'll have it start looking for our app in src/index.ts
and write our bundled app to public/app.js
.
const path = require('path');
module.exports = {
entry: './src/index.ts',
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [ '.ts', '.js' ],
},
output: {
filename: 'app.js',
path: path.resolve(__dirname, 'public'),
},
};
With this complete, we can create a basic Typescript program.
// src/index.ts
function component() {
const element = document.createElement('div');
element.innerHTML = ['Hello,', 'Mojolicious!'].join(' ');
return element;
}
document.body.appendChild(component());
We can then build our Typescript program using Webpack:
$ npx webpack
asset app.js 864 bytes [compared for emit] [minimized] (name: main)
./src/index.ts 196 bytes [built] [code generated]
webpack 5.64.2 compiled in 3123 ms
This creates public/app.js
, which we can then add to our Mojolicious app. To automatically rebuild our app.js
when needed, we can run npx webpack --watch
.
For a complete example, see this sample repository for a Mojolicious/Typescript app. As a bonus, you can get full end-to-end testing for your Mojolicious and Typescript web app using Playwright. With all this, you can bring the best that modern JavaScript has to offer to your Mojolicious web apps!
Top comments (0)