【问题标题】:Import a javascript file globally using webpack ProvidePlugin使用 webpack ProvidePlugin 全局导入 javascript 文件
【发布时间】:2018-06-05 13:56:44
【问题描述】:

我有一个进行网络调用的函数,我希望该函数在全球范围内可用,而无需在每次需要使用该函数时都导入它

请求.js

import 'whatwg-fetch';

/**
 * Parses the JSON returned by a network request
 *
 * @param  {object} response A response from a network request
 *
 * @return {object}          The parsed JSON from the request
 */
function parseJSON(response) {
  if (response.status === 204 || response.status === 205) {
    return null;
  }
  return response.json();
}

/**
 * Checks if a network request came back fine, and throws an error if not
 *
 * @param  {object} response   A response from a network request
 *
 * @return {object|undefined} Returns either the response, or throws an error
 */
function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  const error = new Error(response.statusText);
  error.response = response;
  throw error;

}

/**
 * Requests a URL, returning a promise
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 *
 * @return {object}           The response data
 */
export default function request(url, options) {
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON);
}

Webpack.config.js

    plugins: [
      new webpack.ProvidePlugin({
        fetch: 'exports-loader?self.fetch!whatwg-fetch',
        request : require.resolve(path.join(process.cwd(),'app/utils/request.js'))
      })]

所以当我尝试在任何其他文件中使用请求函数时,它会抛出一个错误,提示“未找到模块”。我还尝试添加一条规则(Shimming),但也失败了。

提前致谢:)

【问题讨论】:

    标签: javascript reactjs webpack react-boilerplate webpack-plugin


    【解决方案1】:

    Webpack docs

    要导入 ES2015 模块的默认导出,您必须 指定模块的默认属性。

    所以只要把你的配置改成这样:

    plugins: [
      new webpack.ProvidePlugin({
        fetch: 'exports-loader?self.fetch!whatwg-fetch',
        request: [path.resolve('app/utils/request.js'), 'default']
      })
    ]
    

    【讨论】:

      猜你喜欢
      • 2017-09-26
      • 2018-05-21
      • 1970-01-01
      • 2020-02-23
      • 2017-12-05
      • 2017-12-02
      • 2016-06-21
      • 1970-01-01
      • 2019-08-08
      相关资源
      最近更新 更多