React 生产构建不同于开发 | polyfill 不会 运行

React production build differs from development | polyfill does not run

我已经 运行 npx create-react-app . 并手动导入了 clip-path。开发构建工作没有问题,但生产构建似乎不起作用。 IE11 和 Edge44 上的问题相同

重现步骤:

  1. npx create-react-app .
  2. 将 "ie 11" 添加到 package.json 中的 browserslist 用于生产和开发
  3. npm i react-app-polyfill
  4. index.js中添加import 'react-app-polyfill/ie11'; import 'react-app-polyfill/stable';
  5. css-shapes-polyfill 抓取 shapes-polyfill.js 并在 .index.html > head 中插入脚本,同时添加浏览器 polyfill。
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js"></script>
<script src='shapes-polyfill.js'></script>
  1. index.html > head
  2. 中包含 <style>
<style>
#polygon-shape-outside {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='200px' height='200px'><polygon points='0,0 142,33 89,141 0,200' fill='rgba(0,0,255, 0.25)'/></svg>");
  shape-outside: polygon(0px 0px, 142px 33px, 89px 141px, 0px 200px);
}
</style>
  1. App
  2. 中插入div
<div style={{
  width: 400,
  fontSize: 10,
  background: 'grey'
}}>
  <div id="polygon-shape-outside"></div>
  <p>Pelicans are a genus of large water birds comprising the family Pelecanidae. They are characterised by a long beak and large throat pouch used for catching prey and draining water from the scooped up contents before swallowing. They have predominantly pale plumage, the exceptions being the Brown and Peruvian Pelicans. The bills, pouches and bare facial skin of all species become brightly coloured before the breeding season. The eight living pelican species have a patchy global distribution, ranging latitudinally from the tropics to the temperate zone, though they are absent from interior South America as well as from polar regions and the open ocean. Fossil evidence of pelicans dates back at least 30 million years, to the remains of a beak very similar to that of modern species recovered from Oligocene strata in France.</p>
</div>

由于 IE 对 SVG 要求严格,图片在 IE 中无法显示。详情可以参考这篇Codepen Blog,重点如下:

  • 大多数浏览器对 charset= 字符串都比较宽容,但 Internet Explorer 需要它。这意味着您需要使用 ;charset=utf8, 而不是 ;utf8,.
  • 您必须 percent-encode 个不是 URL-safe 的字符。例如,<svg>%3Csvg%3E。您可以通过使用单引号 ' 而不是双引号 ".
  • 来最小化需要完成的百分比编码量

据此,我更改了您在 index.html<style> 中的部分代码:

#polygon-shape-outside {
    width: 200px;
    height: 200px;
    float: left;
    background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200px' height='200px'%3E%3Cpolygon points='0,0 142,33 89,141 0,200' fill='rgba(0,0,255, 0.25)'/%3E%3C/svg%3E");
    shape-outside: polygon(0px 0px, 142px 33px, 89px 141px, 0px 200px);
  }

然后它可以运行在所有浏览器的开发模式下都很好。

关于dev模式和prod模式的区别:在<div id="polygon-shape-outside">中添加data-shape-outside="polygon(0px 0px, 142px 33px, 89px 141px, 0px 200px)"。然后内容将环绕图像和页面运行,并且在两种模式和所有浏览器中都完全相同。