代码之家  ›  专栏  ›  技术社区  ›  Ragul Parani

使用webpack provideplugin全局导入javascript文件

  •  2
  • Ragul Parani  · 技术社区  · 8 年前

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

    请求程序

    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'))
          })]
    

    因此,当我尝试在任何其他文件中使用request函数时,它会抛出一个错误,说“module not found”。我也试着增加一条规则( Shimming )也没能成功。

    提前谢谢:)

    1 回复  |  直到 8 年前
        1
  •  3
  •   Fabio Antunes    8 年前

    Webpack docs :

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

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

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