gpt4 book ai didi

javascript - 使用 webpack ProvidePlugin 全局导入 javascript 文件

转载 作者:行者123 更新时间:2023-11-29 18:52:42 25 4
gpt4 key购买 nike

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

请求.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 ),但也没有成功。

提前致谢:)

最佳答案

Webpack docs :

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

所以只需将您的配置更改为如下所示:

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

关于javascript - 使用 webpack ProvidePlugin 全局导入 javascript 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50701951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com