javascript - 如何使用 fetch polyfill、rollup 和 typescript 创建 umd 包?
问题描述
我正在尝试将库与汇总捆绑在一起。
在这个库中,我正在发出 http 请求。当代码在节点上运行时,我想使用fetch
并使用 polyfill。我无法正确配置。它可以在节点上工作但不能在浏览器中工作,或者相反。
这是我的配置文件的样子:
module.exports = [{
input: 'src/mylibrary.ts',
output: {
name: LIB_NAME,
file: getOutputFileName(
resolve(ROOT, pkg.browser),
env === 'production'
),
format: 'umd',
globals: {
fetch: 'cross-fetch',
},
},
plugins: [
typescript({
useTsconfigDeclarationDir: true,
tsconfigOverride: {
allowJs: false,
includes: ['src'],
exclude: ['tests', 'examples', '*.js', 'scripts'],
esModuleInterop: true,
},
}),
nodeResolve({
mainFields: ['jsnext', 'main'],
preferBuiltins: true,
browser: true,
}),
commonjs({
include: ['node_modules/**'],
}),
json(),
env === 'production' ? terser() : {}, // will minify the file in production mode
],
}]
这是我在代码中导入 fetch 的方式:
import 'cross-fetch/polyfill'
在浏览器中效果很好✅</p>
在节点中我有以下错误❌:
throw new Error('unable to locate global object');
^
Error: unable to locate global object
当我查看捆绑的 umd 时,它来自这里:
var getGlobal = function () {
// the only reliable means to get the global object is
// `Function('return this')()`
// However, this causes CSP violations in Chrome apps.
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
};
知道可能是什么问题吗?
解决方案
我忘记添加密钥(cross-fetch
第external
2 行)
以下示例适用于我:
{
input: 'src/meilisearch.ts', // directory to transpilation of typescript
external: ['cross-fetch', 'cross-fetch/polyfill'],
output: {
name: LIB_NAME,
file: getOutputFileName(
// will add .min. in filename if in production env
resolve(ROOT, pkg.browser),
env === 'production'
),
format: 'umd',
sourcemap: env === 'production', // create sourcemap for error reporting in production mode
},
plugins: [
typescript({
useTsconfigDeclarationDir: true,
tsconfigOverride: {
allowJs: false,
includes: ['src'],
exclude: ['tests', 'examples', '*.js', 'scripts'],
esModuleInterop: true,
},
}),
babel({
babelrc: false,
extensions: ['.ts'],
presets: [
[
'@babel/preset-env',
{
modules: false,
targets: {
browsers: ['last 2 versions', 'ie >= 11'],
},
},
],
],
}),
nodeResolve({
mainFields: ['jsnext', 'main'],
preferBuiltins: true,
browser: true,
}),
commonjs({
include: ['node_modules/**'],
}),
json(),
env === 'production' ? terser() : {}, // will minify the file in production mode
],
},
推荐阅读
- ibm-cloud-infrastructure - 需要api将最后上传的item拉到COS bucket
- c++ - 全局时间成本与本地时间成本之和——“for”循环
- c++ - 在陈述“实施定义”时,什么样的软件是“实施”的一部分?究竟什么是“实施”?
- netsuite - Suitescript 2.0 - 如何显示字段并根据下拉列表更新值?
- python - Django:将模型的pk设置为其列中的默认值
- amazon-web-services - 为什么我的 AWS NACL 只允许使用“所有流量”或“所有 TCP”入站规则进行 HTTP 访问?
- algorithm - 参观博物馆的最低费用
- angular - 与其他组件共享属性
- javascript - Javascript:根据具有类的子元素中的值对列表进行排序
- javascript - 带有自定义 Sendgrid 控制器代码的 Strapi Beta 用于电子邮件