Musterknabe
Musterknabe

Reputation: 6081

Compile TypeScript file with imports for browser

I have a .ts file in my project which makes use of imports. These imports, of course, don't work in the browsers, so I want to compile my typescript files to be supported in browsers

{
  "compilerOptions": {
    "noImplicitAny": true,
    "lib": ["es2017", "es7", "es6", "dom"],
    "module": "CommonJS",
    "target": "es5"
  },
  "files": [
    "test.ts"
  ]
}

Just for testing, I added the test.ts. It's contents are

import Axios from "axios";

var axios = Axios.create();
axios.get("https://www.example.com");

Now, when I run the build process, this is the result

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var axios_1 = require("axios");
var axios = axios_1.default.create();
axios.get("https://www.example.com");

And when I use this in my index.html

<script src="test.js"></script>

It simply says ReferenceError: exports is not defined


I can't imagine that it can be so hard and difficult to compile TypeScript using imports to browser-compatible JavaScript. Any help would be greatly appreciated.

Upvotes: 7

Views: 821

Answers (1)

Musterknabe
Musterknabe

Reputation: 6081

It works, when I use webpack and a webpack.config.js which looks like this

const path = require('path');

module.exports = {
    entry: './test.ts',
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            },
        ],
    },
    resolve: {
        extensions: [ '.tsx', '.ts', '.js' ],
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
    },
};

However, do I really need webpack for this? I'm not against webpack and the plan was to use it later on anyway, but still, is there no other way?

Upvotes: 1

Related Questions