首页 > 解决方案 > Rollup 将我的主类名 (SDK) 替换为 default() 名称

问题描述

我正在开发一个库,在我开始进行单元测试之前它一直运行良好。直到几天前,我还可以通过以下方式实例化我的库:

this.belpay = new belpay.SDK('test', {
            username: 'username',
            password: 'password',
            key: 'abc-def',
          });

在我的 chrome 控制台中:

在此处输入图像描述

现在我提出以下错误:

在此处输入图像描述

为了消除此错误,我必须执行以下操作:

this.belpay = new belpay.default('test', {
            username: 'username',
            password: 'password',
            key: 'abc-def',
          });

我不明白为什么现在它显示我默认。我一直在 rollup.config.js 中有这个设置

import nodePolyfills from 'rollup-plugin-node-polyfills';
import babel from 'rollup-plugin-babel';
import serve from 'rollup-plugin-serve';
import commonjs from '@rollup/plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import json from 'rollup-plugin-json';

export default {
  input: 'src/index.js',
  context: 'window',
  output: [
    {
      file: 'dist/belpay.js',
      format: 'umd',
      name: 'belpay',
      exports: 'named',
      globals: ['axios'],
    },
    {
      file: 'dist/belpay.min.js',
      format: 'umd',
      name: 'belpay',
      plugins: [terser()],
      exports: 'named',
    },
  ],
  external: ['axios'],
  plugins: [
    babel({
      exclude: ['node_modules/**'],
      runtimeHelpers: true,
    }),
    nodePolyfills(),
    serve({
      host: 'localhost',
      port: 1234,
      contentBase: 'dist',
      historyApiFallback: true,
      allowCrossOrigin: true,
    }),
    commonjs({
      include: 'node_modules/axios/**',
    }),
    livereload({
      watch: 'dist',
      verbose: true,
    }),
    json(),
  ],
};

[编辑]

我的入口文件(src/index.js)的内容:

export default class SDK {
  #myvar= '';
  #myobject = {};

  method1() {}
  method2() {}
}

这样我在dist/index.html中导入库

<!-- html content -->
...
<!-- at the end of the body tag. -->
<script type="module" src="./belpay.js"></script>
<script type="text/javascript">
  this.belpay = new belpay.SDK();
</script>

这很奇怪,因为在星期五(我们一周的最后一个工作日),我让它运行良好,但在星期一我不能再进行测试了。我没有做任何改变。

欢迎任何改进此文件的建议。

标签: javascriptbundlerrolluprollupjs

解决方案


我发现了问题。我在做:

export default class SDK {}

并且必须这样做:

export class SDK {}

我不必设置“默认”。


推荐阅读