代码之家  ›  专栏  ›  技术社区  ›  jono_hayward

将预定义函数导入ES6模块

  •  0
  • jono_hayward  · 技术社区  · 6 年前

    第一部分: 在master.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 ,我相信它使用巴别塔来传输模块。

    它们被导入到定义选择器函数的同一master.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 );
        } );
    } );
    

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

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

    干杯

    1 回复  |  直到 6 年前
        1
  •  1
  •   Bergi    6 年前

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

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

    而不是在每个模块的顶部重写它们?

    把它们放在自己的模块中,然后导入到任何地方。

    // 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) {
         …
    }