0

第 1 部分:在我的主 .js 文件中,我设置了几个快捷功能:

// Selector shortcuts - mimic jQuery style selectors but using more modern, standard code
const $  = ( selector, scope = document ) => scope.querySelector( selector );
const $$ = ( selector, scope = document ) => scope.querySelectorAll( selector );
const on = ( el, type, listener ) => el.addEventListener( type, listener );

第2部分:

我正在使用 ES6 模块将我的站点的代码拆分为逻辑的、可管理的块。目前我的本地构建设置正在使用Parcel,我相信它使用 Babel 来转换模块。

这些被导入到定义选择器函数的同一个主 .js 文件中:

// Selector shortcuts - mimic jQuery style selectors but using more modern, standard code
const $  = ( selector, scope = document ) => scope.querySelector( selector );
const $$ = ( selector, scope = document ) => scope.querySelectorAll( selector );
const on = ( el, type, listener ) => el.addEventListener( type, listener );

// Load components
import BGVideo    from './BGVideo';
import FieldLabel from './FieldLabel';

// Invoke components
on( document, 'DOMContentLoaded', ( e ) => {

    $$( '[data-background-video]' ).forEach( ( el ) => {
        new BGVideo( el );
    } );

    $$( '.c-form__item' ).forEach( ( el ) => {
        new FieldLabel( el );
    } );
} );

这些在主 .js 文件中工作得很好,但在模块文件中不起作用 - 任何尝试使用它们都会在控制台中触发错误,例如Uncaught ReferenceError: $ is not defined

是否可以在模块文件中访问这些函数,而无需在每个模块的顶部重写它们?

干杯

4

1 回答 1

1

是否可以在模块文件中访问这些功能?

不,它们在主模块的范围内。您可以导出它们并在其他模块中导入它们,但这是不可取的 - 它会在您的入口点上创建循环依赖。

没有在每个模块的顶部重写它们?

只需将它们放在自己的模块中,然后在任何地方导入即可。

// dom_helpers.js
/* Selector shortcuts - mimic jQuery style selectors but using more modern, standard code */
export const $  = (selector, scope = document) => scope.querySelector(selector);
export const $$ = (selector, scope = document) => scope.querySelectorAll(selector);
export const on = (el, type, listener) => el.addEventListener(type, listener);

// master.js
// Load components
import initBGVideo from './BGVideo';
import initFieldLabel from './FieldLabel';
import {$$, on} from './dom_helpers';

// Invoke components
on(document, 'DOMContentLoaded', e => {
    for (const el of $$('[data-background-video]')) {
        initBGVideo(el);
    }
    for (const el of $$('.c-form__item')) {
        initFieldLabel(el);
    }
});

// BGVideo.js
import {$, $$, on} from './dom_helpers';

export default function init(el) {
     …
}
于 2018-08-04T12:48:56.097 回答