问题描述
我正在用 TypeScript 构建一个库,我正在尝试对其进行测试。由于它涉及浏览器 API,我正在使用 @web/test-runner
和 chai
对其进行测试。
我使用的是 TypeScript,一些库是 commonjs 模块,所以我使用 Rollup 将所有这些捆绑到浏览器可以使用的东西中。
我的汇总配置如下:
import typescript from '@rollup/plugin-typescript';
import commonjs from '@rollup/plugin-commonjs';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import json from '@rollup/plugin-json';
import sourceMaps from 'rollup-plugin-sourcemaps';
import { babel } from '@rollup/plugin-babel';
import nodepolyfills from 'rollup-plugin-node-polyfills';
const pkg = require('./package.json');
const libraryName = 'AGreatLibrary';
export default {
input: 'src/index.ts',output: [
{ file: pkg.main,name: libraryName,format: 'umd',sourcemap: true },{ file: pkg.module,format: 'es',],plugins: [
json(),nodepolyfills(),typescript(),commonjs(),nodeResolve({ browser: true,preferBuiltins: false }),sourceMaps(),babel({ babelHelpers: 'bundled',exclude: [/\bcore-js\b/,/\bwebpack\/buildin\b/] }),};
我的 babel 配置
{
"presets":
[
[
"@babel/env",{
"targets":
{
"edge": "17","firefox": "60","chrome": "67","safari": "11.1"
},"useBuiltIns": "usage","corejs": "3"
}
]
],"minified": true
}
我的测试文件
import { Client } from "../lib/index.es.js";
import { expect } from '@esm-bundle/chai';
it('Should create a Client',() => {
let client = new Client("123",true);
expect(client.accesstoken).to.equal("123");
});
it('Should auth',async () => {
let client = new Client("123",true);
let resp = await client.tryAuth();
expect(resp.ok).to.be.true;
});
但是当我运行测试时 (web-test-runner "test/**/*.test.ts" --node-resolve
)
我收到以下错误
? browser logs:
ReferenceError: module is not defined
at node_modules/core-js/internals/global.js:6:0
我不知道该怎么办。
解决方法
我修好了!
plugins: [
commonjs(),json(),nodePolyfills(),typescript(),nodeResolve({ browser: true,preferBuiltins: false }),sourceMaps(),babel({ babelHelpers: 'bundled',exclude: [/\bcore-js\b/,/\bwebpack\/buildin\b/] }),],
commonjs
应该在数组的顶部。