简体   繁体   English

如何将babel-polyfill用于多个分离的条目/输出?

[英]How can I use babel-polyfill for multiple separated entries / outputs?

I have this in my webpack.config.js to create two different outputs from two sources: 我在webpack.config.js有这个来从两个源创建两个不同的输出:

module.exports = {
  entry: {
    'dist/index.js': ['babel-polyfill', './src/Component.jsx'],
    'example/bundle.js': ['babel-polyfill', './src/Page.jsx'],
  },
  output: {
    path: './',
    filename: '[name]',
  },
  ...

Compiling it with webpack works just fine, but if I load index.js in a browser I get this error: 使用webpack编译它可以正常工作,但如果我在浏览器中加载index.js ,我会收到此错误:

Uncaught Error: only one instance of babel-polyfill is allowed 未捕获的错误:只允许一个babel-polyfill实例

I need babel-polyfill for both outputs. 我需要babel-polyfill用于两个输出。 What can I do? 我能做什么?

When developing a library (as opposed to an application), the Babel team does not recommend including babel-polyfill in your library. 在开发库(而不是应用程序)时,Babel团队不建议在库中包含babel-polyfill We recommend either: 我们建议:

  1. Assume the ES6 globals are present, thus you'd instruct your library users to load babel-polyfill in their own codebase. 假设存在ES6全局变量,因此您将指示库用户在自己的代码库中加载babel-polyfill
  2. Use babel-runtime by enabling babel-plugin-transform-runtime , which attempts to analyze your code to figure out what ES6 library functionality you are using, then rewrites the code to load the polyfilled logic from babel-runtime instead of from the global scope. 通过启用babel-plugin-transform-runtime来使用babel-runtime ,它会尝试分析您的代码以确定您正在使用的ES6库功能,然后重写代码以从babel-runtime而不是全局范围加载polyfilled逻辑。 One downside of this approach is that it has no way to polyfill new .prototype methods like Array.prototype.find since it can't know if foo.find is an array. 这种方法的一个缺点是它无法.prototypeArray.prototype.find这样的新.prototype方法,因为它无法知道foo.find是否是一个数组。

So my recommendation would be to remove babel-polyfill from your dist/index.js bundle entirely. 所以我的建议是完全从你的dist/index.js包中删除babel-polyfill

Use idempotent-babel-polyfill 使用idempotent-babel-polyfill

import 'idempotent-babel-polyfill';

https://github.com/codejamninja/idempotent-babel-polyfill https://github.com/codejamninja/idempotent-babel-polyfill

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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