使用ts编写的npm包如何打包成IE11能兼容的方式?

最近在看skywalking-client-js(使用ts编写的项目),发现其项目打包后代码没做IE11兼容处理,比如代码中存在箭头函数、const声明,请问该如何配置才能将箭头函数、const变量等转换?。在项目中tsconfig.json,代码如下:

{
  "compilerOptions": {
    "declaration": true,
    "outDir": "./lib/",
    "noImplicitAny": true,
    "sourceMap": true,
    "module": "es6",
    "target": "es5",
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "moduleResolution": "node"
  }
}

尝试安装配置了babel-loader,可能方式不太对,没起到效果。
原相关webpack配置如下:

const config = {
  entry: './src/index.ts',
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: 'ts-loader'
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
    mainFiles: ['index'],
  },
  output: {
    filename: 'index.js',
    path: path.resolve(__dirname, 'lib'),
    publicPath: '/',
  },
  plugins: [
    new WebpackConcatPlugin({
      bundles: [
        {
          dest: './lib/src/types.d.ts',
          src: './src/**/*.d.ts',
        },
      ],
    }),
  ],
  devServer: {
    contentBase: './lib',
    hot: true,
  },
  optimization: {
    moduleIds: 'named',
  },
};
阅读 4k
2 个回答

最终问题改法如下:

# 安装babel相关依赖
yarn add babel-loader @babel/core babel-preset-env -D

# 写入babel配置
touch .babelrc
echo "{\"presets\": [\"env\"]}" >> .babelrc
// webpack配置如下,在原先基础上添加babel-loader和箭头函数解析配置
const config = {
  entry: './src/index.ts',
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: ['babel-loader', 'ts-loader']
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
    mainFiles: ['index'],
  },
  output: {
    filename: 'index.js',
    path: path.resolve(__dirname, 'lib'),
    publicPath: '/',

    // 箭头函数转换
    environment: {
      arrowFunction: false,
    },
  },
  plugins: [
    new WebpackConcatPlugin({
      bundles: [
        {
          dest: './lib/src/types.d.ts',
          src: './src/**/*.d.ts',
        },
      ],
    }),
  ],
  devServer: {
    contentBase: './lib',
    hot: true,
  },
  optimization: {
    moduleIds: 'named',
  },
};

使用awesome-typescript-loader,不要使用ts-loader,在你的tsconfig配置如下:

    "useBabel": true,
    "babelOptions": {
      "babelrc": false,
      "presets": [
        [
          "@babel/preset-env",
          {
            "targets": "last 2 versions, ie 11",
            "modules": false
          }
        ]
      ]
    },
    "babelCore": "@babel/core",
    "reportFiles": [
      "**/*.ts",
      "**/*.tsx"
    ]
  }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题