简体   繁体   中英

Import a javascript file globally using webpack ProvidePlugin

I have a function to make network calls and i want that function to be globally available without me having to import it every time i need to use the function

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

So when i try to use the request function in any other file, it throws an error saying 'Module not found'. I had also tried to add a rule( Shimming ), which also failed to work.

Thanks in advance :)

In the Webpack docs :

For importing the default export of an ES2015 module, you have to specify the default property of module.

So just change your config to something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM