编译带有浏览器导入的 TypeScript 文件

Mus*_*abe 7 javascript typescript ecmascript-6

我的项目中有一个.ts使用导入的文件。当然,这些导入在浏览器中不起作用,因此我想编译我的打字稿文件以使其在浏览器中受支持

{
  "compilerOptions": {
    "noImplicitAny": true,
    "lib": ["es2017", "es7", "es6", "dom"],
    "module": "CommonJS",
    "target": "es5"
  },
  "files": [
    "test.ts"
  ]
}
Run Code Online (Sandbox Code Playgroud)

只是为了测试,我添加了test.ts. 其内容是

import Axios from "axios";

var axios = Axios.create();
axios.get("https://www.example.com");
Run Code Online (Sandbox Code Playgroud)

现在,当我运行构建过程时,这就是结果

"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");
Run Code Online (Sandbox Code Playgroud)

当我在我的中使用它时index.html

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

它只是说ReferenceError: exports is not defined


我无法想象使用与浏览器兼容的 JavaScript 的导入来编译 TypeScript 会如此困难。任何帮助将不胜感激。

Mus*_*abe 1

当我使用 webpack 和一个webpack.config.js看起来像这样的东西时它起作用了

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'),
    },
};
Run Code Online (Sandbox Code Playgroud)

但是,我真的需要 webpack 吗?我并不反对 webpack,并且计划稍后使用它,但是仍然没有其他方法吗?

  • 您仍然无法使用基本 Typescript 选项来编译可用于浏览器的内容,这有点令人遗憾;我不想配置一些捆绑工具的负载,这会减慢构建和调试的速度,只是为了使用 Typescript 导入..疯狂,2020 年了! (3认同)