8

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.

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Its a bit pants that you still cannot use base Typescript options to compile something usable for browsers; I dont want to configure some load of bundling tools which will slow down builds and debugging just to use Typescript imports .. madness, its 2020!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.