I started with a question: how can I write Typescript modules to run in a Web browser without using Webpack or some other bundler?
I’ve used TypeScript for programming in Nodejs, and for writing user interfaces. These interface run in Web browsers and on mobile devices (mostly using React and React Native). When targeting the Web, I can start from a template like create-react-app. But, that uses Webpack under the hood. Also, using a UI component library is outside the scope of this project.
I can compile the TypeScript to JavaScript and import that into my Web document using a script
tag. But then all the code that I want to include on the page needs to be written in one file. I don’t want to do that, so what else can I do?
The Setup
This is how my project is structured.
src/ main.ts Class1.ts Class2.ts types.ts static/ js/ index.html style.css tsconfig.json
Notice there is currently no JavaScript files in the js
directory. This is where I want to transpiled the Typescript to go. The main.ts
will be the main method for programming the index.html
. I’ll use all the classes and the types file in the main file.
TypeScript Config
Here’s the tsconfig.json
file I’m using to accomplish my goal.
{ "compilerOptions": { "target": "es2016", "module": "AMD", "rootDir": "./src", "outFile": "./static/js/script.js", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true } }
For the most part, this is the default configuration. I’ve added entries for module
, rootDir
, and outFile
. The key here is compiling the sources under the rootDir
, to an AMD module
in the outFile
.
AMD Loader
Since we’ll be using AMD modules, we’ll need an AMD module loader in our Web document. I got that from the Dojo CDN by adding the following script
tag to my index.html
file.
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
Conclusion
Now, all the elements are in place:
- A Web document (
static/index.html
) - An AMD loader in our Web document
- Typescript source code (
src/
) - A
tsconfig.json
for transpiling our source into JavaScript AMD modules
The last thing we need to do is have typescript perform the transpiling and include our main.js
file in our Web document.
This approach shows how we can write Typescript modules to run in a Web browser without using Webpack or some other bundler.