首页 > 解决方案 > 使用 Webpack 将 TypeScript 转为 es5

问题描述

我创建了一个非常简单的环境来试验 TypeScript 和 Webpack。我尽可能地遵循在线示例,但构建的输出 contains () =>,它应该已更改为 ES5 语法。请注意,我没有使用 Babel——据我所知,TypeScript 应该能够在没有它的情况下生成 ES5。

这是我的 package.json 的一部分:

  "devDependencies": {
    "ts-loader": "8.0.7",
    "typescript": "4.0.3",
    "webpack": "5.2.0",
    "webpack-cli": "4.1.0",
    "webpack-dev-server": "3.11.0"
  },
  "scripts": {
    "build": "webpack"
  },

这是我的 tsconfig.json:

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "es2020",
        "target": "ES5",
        "allowJs": true
    }
}

这是 webpack.config.js:

const path = require('path');

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

这是 src/index.ts:

export const myObj = {
    visual: "the visual",
    audio: "the audio"
}

完成后,我npm run build在 dist/my-library.js 中得到以下信息:

(()=>{"use strict";var r={607:(r,e,t)=>{}},e={};function t(o){if(e[o])return e[o].exports;var n=e[o]={exports:{}};return r[o](n,n.exports,t),n.exports}t.d=(r,e)=>{for(var o in e)t.o(e,o)&&!t.o(r,o)&&Object.defineProperty(r,o,{enumerable:!0,get:e[o]})},t.o=(r,e)=>Object.prototype.hasOwnProperty.call(r,e),t(607)})();

请注意,即使我指定了“ES5”,代码也不会在旧浏览器上运行。

文件夹结构为:

dist
  my-library.js
src
  index.ts
package.json
tsconfig.json
webpack.config.js

我错过了什么?谢谢。

标签: javascripttypescriptwebpackecmascript-5

解决方案


您可能正在使用webpack5which 引入了对 es6+ 的支持作为target. 您看到的代码是 Webpack 生成的代码(它是运行时代码),您可以指定它应该使用es5.

// webpack.config.js

const path = require('path');

module.exports = {
    entry: './src/index.ts',
    devtool: 'inline-source-map',
    target: ['web', 'es5']
    // ------ ^
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            },
        ],
    },
    resolve: {
        extensions: [ '.tsx', '.ts', '.js' ],
    },
    output: {
        filename: 'my-library.js',
        path: path.resolve(__dirname, 'dist'),
    },
};

有关更多选项,请查看文档


推荐阅读