引入npm包中TextField类时出现‘Textfield is not a constructor’错误求助
问题
我遇到了错误:Textfield is not a constructor。我知道有很多相关问题,但查看了约12个后仍未找到解决办法。
我正在开发我的第一个npm包,其中包含一些简化Cypress编写的辅助类。以下是我希望通过npm包加载的其中一个类:
// node_modules/prueba-para-oskar/src/Helpers/Fields/TextField.js class TextField { /** * * @param {string} value * @param {string} selector * @param {object} options */ type(value, selector, options) { this[options.widget](value,selector); } /** * * @param {string} value * @param {string} selector */ ckeditor(value, selector){ cy.ckeditor(value, selector) } noCkeditor(value, selector){ cy.get(selector).type(value); } } module.exports = TextField;
我的包index.js如下:
// node_modules/prueba-para-oskar/src/index.js const TextField = require('./Helpers/Fields/TextField'); module.exports = { TextField }
我的Cypress页面对象代码如下:
// cypress/e2e/pages/ArticlePage.js // 如果从Cypress同目录加载类(非npm包),可以正常工作 import { Property } from "../../support/Helpers/lib/Property"; import { Submit } from "../../support/Helpers/lib/Submit"; import { FileField } from "../../support/Helpers/Fields/FileField"; import { TextAreaField } from "../../support/Helpers/Fields/TextAreaField"; // import { TextField } from "../../support/Helpers/Fields/TextField"; import { TextField } from "prueba-para-oskar"; export default class ArticlePage { article_path = "/node/add/article"; tagInput = 'input[data-drupal-selector="edit-field-tags-target-id"]'; submitButton = 'input[data-drupal-selector="edit-submit"]'; constructor() { this.Property = new Property(); this.FileField = new FileField(); this.TextAreaField = new TextAreaField(); this.TextField = new TextField(); this.Submit = new Submit(); } userCanAccesArticlePage() { cy.visit(this.article_path, { failOnStatusCode: true }); } havePermissionsToSeeNodeAddArticle() { cy.location("pathname").should("eq", this.article_path); } clickSubmitButttom() { cy.get(this.submitButton).click(); } }
当尝试在ArticlePage.js中加载来自npm包的TextField类时出现上述错误,请问该如何正确加载npm包中的类到页面对象类中?
解决方案
1. 检查npm包的入口配置
确认你的npm包package.json里的main字段是否正确指向入口文件。如果源码在src目录,main需配置为:
{ "main": "src/index.js" }
若后续做了打包编译,要将main改为编译后的文件路径,比如dist/index.js,否则会导致导入的内容不符合预期。
2. 统一模块语法(解决CommonJS与ES模块混用问题)
你的npm包用module.exports(CommonJS)导出,而Cypress文件用import(ES模块)导入,可能存在兼容问题,可二选一调整:
改为ES模块导出:
修改TextField.js和index.js的导出语法:// TextField.js export default TextField; // index.js import TextField from './Helpers/Fields/TextField'; export { TextField };同时在包的
package.json中添加:"type": "module"改用CommonJS导入:
将ArticlePage.js中的导入改为require:const { TextField } = require("prueba-para-oskar");
3. 确认npm包安装/链接状态
如果是本地开发npm包,需确保通过npm link将本地包链接到Cypress项目,或直接用相对路径安装(如npm install ../prueba-para-oskar),避免因包未正确安装导致导入失败。
4. 调整Cypress模块解析配置
若以上方法无效,可修改cypress.config.js,确保能正确解析npm包模块:
const { defineConfig } = require("cypress"); module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { // 其他配置 }, resolve: { extensions: ['.js', '.json'], } }, });
内容的提问来源于stack exchange,提问作者Oskar Calvo

