【问题标题】:Import a jQuery plugin in a module在模块中导入 jQuery 插件
【发布时间】:2017-09-16 23:05:02
【问题描述】:

我正在尝试使用 npm 导入一个 jQuery 插件 (js-offcanvas),但我一直收到同样的错误:

app.js:20: Uncaught TypeError: $(...).offcanvas is not a function

app.js 文件:

import offcanvas from "js-offcanvas"

$('#off-canvas').offcanvas({
  // options
});
$( function(){
  $(document).trigger("enhance");
});

html 文件:

<body>
  <div class="c-offcanvas-content-wrap">
    ...
    <a href="#off-canvas" data-offcanvas-trigger="off-canvas">Menu</a>
    ...
  </div>
  <aside id="off-canvas"></aside>
</body> 

我不确定我是否做错了什么。

更新 这是我的 brunch-config.js 文件:

exports.config = {
// See http://brunch.io/#documentation for docs.
files: {
  javascripts: {
    joinTo: "js/app.js"

    // To use a separate vendor.js bundle, specify two files path
    // https://github.com/brunch/brunch/blob/master/docs/config.md#files
    // joinTo: {
    //  "js/app.js": /^(js)/,
    //  "js/vendor.js": /^(vendor)|(deps)/
    // }
    //
    // To change the order of concatenation of files, explicitly mention here
  // https://github.com/brunch/brunch/tree/master/docs#concatenation
  // order: {
  //   before: [
  //     "vendor/js/jquery-2.1.1.js",
  //     "vendor/js/bootstrap.min.js"
  //   ]
  // }
    },
    stylesheets: {
      joinTo: "css/app.css"
    },
    templates: {
      joinTo: "js/app.js"
    }
  },

  conventions: {
    // This option sets where we should place non-css and non-js assets in.
    // By default, we set this to "/assets/static". Files in this directory
    // will be copied to `paths.public`, which is "priv/static" by default.
    assets: /^(static)/
  },

  // Phoenix paths configuration
  paths: {
    // Dependencies and current project directories to watch
    watched: ["static", "css", "js", "vendor"],
    // Where to compile files to
    public: "../priv/static"
  },

  // Configure your plugins
  plugins: {
    babel: {
      // Do not use ES6 compiler in vendor code
      ignore: [/vendor/]
    }
  },

  modules: {
    autoRequire: {
      "js/app.js": ["js/app"]
    }
  },
npm: {
    enabled: true,
    globals: {
      $: 'jquery',
      jQuery: 'jquery',
    }
  }
};

【问题讨论】:

  • 你导入 jquery 了吗?
  • 是的,我更新了问题以显示 brunch-config.js 文件
  • 我真的很想帮助你,但我想不通。但是可以肯定的是,您不能像这样或以其他方式导入插件,因为插件不支持它。它只能通过全局空间工作。在我看来,把它放在一边。 ;)

标签: javascript jquery phoenix-framework brunch off-canvas-menu


【解决方案1】:

像这样尝试 npm.static:

npm: {
  static: ['node_modules/${plugin-name}/${js-path}']
}

这会将选定的文件包含到连接的文件中。 更多信息请关注docs

npm.static: 数组:npm 包中的 javascript 文件列表按原样包含,无需分析它们的依赖关系或将它们包装到模块中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多