Require.js 加载 CDN bootstrap 和 CDN popper

Require.js load CDN bootstrap and CDN popper

我希望使用 require.js 加载 CDN 托管 bootstrap 和 jquery。

我知道之前有人问过这个问题(参考 Steve Eynon 对 的回答),但发布的答案对我不起作用。

到目前为止我尝试了什么

主机 html 文件有内容...

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script data-main="js/market-place" src="js/lib/requirejs/require.min.js"></script>
</head>   
<body>
 html content etc.
</body>
</html>

文件js/market-place.js 有内容...

console.log( 'market-place.js');

requirejs(['./decision-market-common'], function(){
  console.log( 'common requirement met.');
  require(['bootstrap'], function( bootstrap){
    console.log( 'bootstrap requirement met.');
    });
  });

文件js/decision-market-common.js 有内容...

console.log( 'decision-market-common.js');

requirejs.config({
  paths: {
    jquery   : 'https://code.jquery.com/jquery-3.3.1.slim.min',
    popper   : 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min',
    bootstrap: 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min'
    },
  shim: {
    bootstrap: {
      deps: ['jquery', 'globalPopper']
      }
    }
  });


define( 'globalPopper', ['popper'], function( p){
  window.Popper = p;
  console.log( 'global Popper is set.');
  return p;
  });

结果

使用 Chrome 作为我的开发浏览器,我得到以下结果,首先在 javascript 控制台中...

market-place.js
decision-market-common.js
common requirement met.
global Popper is set.

但是我得到 javascript 错误:

Failed to load resource: net::ERR_FILE_NOT_FOUND

require.js 正在尝试加载 ./popper.js,即使它已成功加载 CDN popper.js!为什么?

答案是...

使用 bootstrap 版本 4.0.0-beta。版本 4.0.0-beta 有效,但任何更高版本(4.0.0 到 4.1.3)在 requirejs 支持方面都被破坏了。

另一种方法是使用 bootstrap 的捆绑版本,然后您可以使用最新版本并且不需要 link popper。没有 bundle bootstrap 的 CDN,因此您需要制作一个本地副本。在这种情况下,文件 js/decision-market-common.js 看起来像:

需要明确 console.log('decision-market-common.js');

requirejs.config({
  paths: {
    jquery   : 'https://code.jquery.com/jquery-3.3.1.slim.min',
    bootstrap: 'lib/bootstrap/bootstrap.bundle.min'
    },
  shim: {
    bootstrap: {
      deps: ['jquery']
      }
    }
  });

另外,一个小问题:使用 requirejs() 而不是 require() 更好(我认为?)。

这个问题的答案不适合我。

我的场景是:

  • 使用 Bootstrap 4.1.3(无法移动到不同的版本)
  • 无法使用捆绑版本,因为我想更改 Popper 中的默认设置(具体来说,禁用 GPU 加速以解决工具提示中文本模糊的一些问题)

使用捆绑版本,我无法访问 Popper "inside" Bootstrap 版本来更改默认值。

最终,我在 RequireJS (https://requirejs.org/docs/api.html#config-map) 中遇到了 "map" 选项。我将其添加到我的 RequireJS 配置中:

map: {
    '*': {
        'popper.js': 'popper'
    }
}

这导致 RequireJS 正确解析 Popper。

这不是一个完美的解决方案,我不能保证它对其他任何人都有效,但我在这方面花了一些时间,所以我希望这对某人有所帮助!