首页 > 解决方案 > 排除外部库捆绑在 webpack 中?

问题描述

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

这是一个基于 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
  }
};

索引.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>

标签: javascripthtmlwebpackbundler

解决方案


我找到了解决方案。

matter-js 属性是指来自 node-modules 的库,值是指要从捆绑中排除的全局对象。

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


推荐阅读