我使用了纯 Gulp,在编译时,我得到了这样的输出:
class useShowPassword {
constructor(button, input) {
if (!button || !input) throw 'Элементы не найдены';
this.button = button;
this.input = input;
button.addEventListener('click', () => this.toggleAttribute());
}
toggleAttribute() {
const status = this.input.getAttribute('type') === 'text';
this.input.setAttribute('type', status ? 'password' : 'text');
status ? this.button.classList.remove('active') : this.button.classList.add('active');
}
}
我将 Rollup 与模块连接起来,代码开始看起来像这样:
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define('showPassword', factory) :
(global = global || self, global.showPassword = factory());
}(this, (function () { 'use strict';
class useShowPassword {
constructor(button, input) {
if (!button || !input) throw 'Элементы не найдены';
this.button = button;
this.input = input;
button.addEventListener('click', () => this.toggleAttribute());
}
toggleAttribute() {
const status = this.input.getAttribute('type') === 'text';
this.input.setAttribute('type', status ? 'password' : 'text');
status ? this.button.classList.remove('active') : this.button.classList.add('active');
}
}
return useShowPassword;
})));
在html
我试图包含一个文件并使用它的功能:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<title></title>
<link rel="stylesheet" type="text/css" href="css/app.css" />
</head>
<body>
<!-- // -->
<script src="js/app.js"></script>
<script>
const button = document.querySelector('.button');
const input = document.querySelector('.input');
new useShowPassword(button, input);
</script>
</body>
</html>
因此,我收到一个错误:Uncaught ReferenceError: useShowPassword is not defined
文件本身gulpconfig.js
只改变了一行:
.pipe(rollup({ plugins: [babel(), resolve(), commonjs()] }, 'umd'))
这不是配置的问题,而是如何在项目中使用构建的文件。
upd:代码本身,它可以工作,我只是无法访问该类,因为 它是在使用Rollup
'a
我分析了代码并通过反复试验发现了问题。
我将举一个未汇编代码的示例:
我们正在导出两个类,
foo
和bar
.组装后看起来像这样:
如果您注意到 top
define('showPassword')
,您可以猜测您需要参考它才能访问之后的类。在输出端,我必须编写如下代码:
我使用定义的名称和导出的名称,最后我可以根据需要使用该类。一切正常。