简体   繁体   中英

Exclude external library from being bundled in webpack?

I'm trying to configure webpack in order that I can import libraries but they won't be bundled with my code and instead will be served from a CDN that's linked on the html file. I read about this implementation on a blog post but forgot how to do it.

It's a small project based on matter-js library.

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>

I have found the solution.

The matter-js property refers to the library from node-modules and the value refers to the global object that you want to exclude from bundling.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM