How to load AMD modules from external file using webpack

Bas*_*ter 5 javascript module amd require webpack

Working on a project I came across the case where I need to load a third party file written as AMD modules using a script tag: <script type="text/javascript" src="https://cdn.host.com/external.js"></script>.

The file contains multiple modules which the example code uses like:

require(['src/module/MyObject'], (myObject) => {
 // Use myObject
});
Run Code Online (Sandbox Code Playgroud)

The example includes RequireJS as a script tag to enable this syntax. Now...my project is a React app with Webpack in which I would like to access 'myObject' somewhere in a component but I cannot seem to get this to work.

仅使用 require() 语法会失败,因为 Webpack 尝试将代码添加到包中。我尝试了“ non_webpack_require ”替代方案,保留了 RequireJS 脚本标签,但这似乎在代码的其他地方添加了各种冲突(到处都是未定义的东西)。我也尝试摆弄 webpack 'External' 属性,但似乎也无法让它按预期工作。后者似乎是要走的路,但我最终得到 'src/module/MyObject' is undefined 错误。

任何帮助表示赞赏。

编辑:根据要求,我的 webpack.config 的相关部分:

{
  entry: './src/index.tsx',

  output: {
    path: path.join(__dirname, 'dist'),
    publicPath: '/',
    filename: `js/[name].[contenthash].bundle.js`,
    chunkFilename: 'js/[name].[contenthash].js',
  },

  resolve: {
    // Add '.ts' and '.tsx' as resolvable extensions.
    extensions: ['.ts', '.tsx', '.js', '.json'],
    plugins: [
      new TsconfigPathsPlugin(),
    ],
  },

  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: {
          loader: "babel-loader",
        },
        exclude: [/node_modules/],
      },
    ],
  },
}
Run Code Online (Sandbox Code Playgroud)

jon*_*y89 0

我认为你使用了错误的例子。

RequireJS是一个不同的旧模块解析器。通常,您不应该在同一个项目中拥有webpack同样的功能。Requirejs有一些边缘情况,但这不是其中之一。

我在你提供的那个库中看了一点,他们确实有 es6 模块包,你应该看看下面的例子:

https://github.com/bitmovin/bitmovin-player-web-samples/tree/master/webpack-demo

这将是最好的方法。

如果您出于某种原因仍然想使用他们的 CDN,那么最适合您的是:

https://cdn.bitmovin.com/player/web/8/bitmovinplayer.js

请在此处查看完整的演示存储库(他们也做出了反应)

https://github.com/bitmovin/bitmovin-player-web-samples