子文件夹中的模块与webpack

时间:2018-01-22 09:22:32

标签: javascript webpack gulp browserify

我使用 blendid 创建了一个新的应用程序,将一个美妙的gulp任务组合成一个可配置的资产管道和静态网站构建器

html

 <h1 data-module="hoverEnlarge">{{ message }}</h1>

js结构

app.js
|_____ modules
      |_______index.js
      |_______hoverEnlarge.js

js - app.js

import './modules'
console.log(`app.js has loaded!`)

js - modules / index.js

/*
  Automatically instantiates modules based on data-attributes
  specifying module file-names.
*/

const moduleElements = document.querySelectorAll('[data-module]')

for (var i = 0; i < moduleElements.length; i++) {
  const el = moduleElements[i]
  const name = el.getAttribute('data-module')
  const Module = require(`./${name}`).default
  new Module(el)
}

/*
  Usage:
  ======

  html
  ----
  <button data-module="disappear">disappear!</button>

  js
  --
  // modules/disappear.js
  export default class Disappear {
    constructor(el) {
      el.style.display = 'none'
    }
  }
*/

js - modules / hoverEnlarge.js

import anime from 'animejs';

export default class hoverEnlarge {
  constructor(el) {
    var buttonEl = el;

function animateButton(scale, duration, elasticity) {
  anime.remove(buttonEl);
  anime({
    targets: buttonEl,
    scale: scale,
    duration: duration,
    elasticity: elasticity
  });
}

function enterButton() { animateButton(1.2, 800, 400) };
function leaveButton() { animateButton(1.0, 600, 300) };

buttonEl.addEventListener('mouseenter', enterButton, false);
buttonEl.addEventListener('mouseleave', leaveButton, false);
    console.log(el.textContent, '- Enlarge hover effect')
  }
}

这个工作。如前所述,h1 data-module =&#34; hoverEnlarge&#34;指的是它的模块。

hoverEnlarge 是一种悬停效果。我想创建带有效果的js文件夹,以包含在将来的项目中,只需克隆此存储库。所以,我们有hoverEnlarge.js,hoverReduce.js,hoverSelect.js等等。

有什么问题? 子文件夹不起作用。如果我想要这样的结构:

app.js
|_____ modules/
      |_______index.js
      |_______hoverEffects/
      |        |_______hoverEnlarge.js
      |        |_______hoverReduce.js
      |        |_______hoverSelect.js
      |________otherEffectsFolder/
               |________effect1.js
               |________effect2.js

如果我尝试将hoverEnlarge放在这里:js / modules / hover / hoverEnlarge.js它会起作用,我会收到此错误

ERROR in /Applications/MAMP/htdocs/crystal/src/javascripts/animejs/index.js
Module build failed: Error: ENOENT: no such file or directory, open '/Applications/MAMP/htdocs/crystal/src/javascripts/animejs/index.js'
 @ /Applications/MAMP/htdocs/crystal/src/javascripts/modules/hover/hoverEnlarge.js 3:0-28
 @ /Applications/MAMP/htdocs/crystal/src/javascripts/modules ^\.\/.*$
 @ /Applications/MAMP/htdocs/crystal/src/javascripts/modules/index.js
 @ /Applications/MAMP/htdocs/crystal/src/javascripts/app.js
 @ multi webpack-hot-middleware/client?reload=true&noInfo=false&quiet=true&react=false ./app.js

我该怎么办?

1 个答案:

答案 0 :(得分:0)

解决。

只需将完整路径放在数据模块

<h1 data-module="path/to/file">{{ message }}</h1>