排除外部库被捆绑在 webpack 中?

Exclude external library from being bundled in webpack?

我正在尝试配置 webpack 以便我可以导入库,但它们不会与我的代码捆绑在一起,而是从 html 文件上链接的 CDN 提供。我在博客 post 上读到了这个实现,但忘记了如何去做。

这是一个基于matter-js库的小项目。

webpack.config.js

module.exports = {
  mode: "production",
  entry: "./src/index",
  target: "web",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: ["babel-loader"]
      },
      {
        test: /\.html$/,
        use: ["html-loader"]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: "index.html",
      template: path.join(__dirname, "./src/index.html"),
      scriptLoading: "defer",
      inject: "body"
    })
  ],
  devServer: {
    contentBase: path.join(__dirname, "dist"),
    compress: false,
    port: 3000,
    hot: true,
    open: true
  }
};

index.html

<body>
    <!-- Matter JS CDN-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.14.2/matter.min.js"></script>

    <!-- The bundle will be injected here-->
  </body>

我找到了解决方案。

matter-js 属性 引用来自节点模块的库,值引用要从捆绑中排除的全局对象。

module.exports = {
  //...
  externals: {
    "matter-js": "Matter"
  },
  //...
};