【问题标题】:Not able to use custom functions in webpack with require无法在 webpack 中通过 require 使用自定义函数
【发布时间】:2016-11-30 11:01:11
【问题描述】:

我正在使用 react 和 webpack 创建一个渐进式网络应用程序。 我已成功配置所有内容并能够开始开发。 现在,我有很多辅助函数,例如:

function getCookie(name) {
      var start = document.cookie.indexOf(name + "=");
      var len = start + name.length + 1;
      if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return null;
      }
      if (start == -1) return null;
      var end = document.cookie.indexOf(';', len);
      if (end == -1) end = document.cookie.length;
      return unescape(document.cookie.substring(len, end));
}

因此,为此我创建了另一个 js 文件:helper.jsx。 现在我的 helper.js 包含上面的函数。现在我想在另一个反应组件中使用上述功能。

我在我的组件中做一个要求:

var helper = require("helper");

并尝试使用以下方法调用函数:

helper.getCookie('user');

这给了我 helper.getCookie 没有定义。 请告诉我如何创建一个 helper js 并在我的 react 组件中使用 helper js 的功能。

【问题讨论】:

标签: reactjs webpack require


【解决方案1】:

您需要使用 module.exports 导出函数:

function getCookie(name) {
      var start = document.cookie.indexOf(name + "=");
      var len = start + name.length + 1;
      if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return null;
      }
      if (start == -1) return null;
      var end = document.cookie.indexOf(';', len);
      if (end == -1) end = document.cookie.length;
      return unescape(document.cookie.substring(len, end));
}

module.exports = {
    getCookie: getCookie
};

【讨论】:

  • Thanx Ori,只是另一个上下文不同的问题。我在我的项目中对我项目的库文件夹中的一个 php 文件进行了一些 ajax 调用。那么如何让我的 php 文件在 webpack 服务器中执行呢?
  • 有什么办法可以在 webpack 服务器中执行 php 文件吗?或者我应该将整个项目包含在将在不同端口上运行的不同服务器中?
  • 据我所知,您无法在 webpack 开发服务器中执行 php 文件,但我已经很久没有接触过 PHP。第二个解决方案应该可以工作,但是你必须在你的 PHP 服务器上启用 CORS,我真的不知道该怎么做。
猜你喜欢
  • 1970-01-01
  • 2017-12-27
  • 2017-07-23
  • 2018-11-06
  • 1970-01-01
  • 2017-09-25
  • 2019-12-26
  • 1970-01-01
  • 2023-03-13
相关资源
最近更新 更多