在不包含对等依赖项的情况下构建 Webpack [英] Webpack to build without including peer dependencies

查看:29
本文介绍了在不包含对等依赖项的情况下构建 Webpack的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 React 库并使用 Webpack 对其进行捆绑.我很清楚依赖和对等依赖背后的概念.

I am building a React library and using Webpack to bundle it. I'm well aware of the concept behind dependencies and peer dependencies.

在项目中,React 被指定为对等依赖.

In the project, React is specified as a peer dependency.

"peerDependencies": {
  "react": ">= 16.3.0",
  "react-dom": ">= 16.3.0"
}

这是我的build脚本

"build": "webpack --config webpack.config.babel.js"

这是我的webpack.config.babel.js

import path from 'path';
import CleanWebpackPlugin from 'clean-webpack-plugin';
const packageJson = require('./package.json');

export default () => ({
  mode: 'production',
  entry: {
    index: path.join(__dirname, 'src/index.js')
  },

  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
    library: packageJson.name,
    libraryTarget: 'umd'
  },

  module: {
    rules: [
      {
        test: /.jsx?$/,
        exclude: /node_modules/,
        include: path.join(__dirname, 'src'),
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env', '@babel/preset-react']
            }
          }
        ]
      },
      {
        test: /\.(scss)$/,
        loader: 'style-loader!css-loader!sass-loader'
      }
    ]
  },

  resolve: {
    extensions: ['.js', '.jsx', '.scss']
  },

  plugins: [new CleanWebpackPlugin(['dist/*.*'])],
  optimization: {
    splitChunks: {
      name: 'vendor',
      minChunks: 2
    }
  }
});

每次我构建时,React 代码都会包含在捆绑文件中.我不确定如何在捆绑文件中不包含 React 的情况下捆绑库.

Every time I build, React code is included in the bundled file. I'm unsure about how to bundle the library without including React in the bundled file.

推荐答案

我想通了.

Webpack 有一个名为 externals 的配置.任何指定为外部的东西都不会捆绑在一起.

Webpack has a configuration called externals. Anything specified as an external will not be bundled together.

我所要做的就是将此配置添加到 webpack.config.babel.js

All I had to do was to add this config to webpack.config.babel.js

externals: {
  react: 'react',
  reactDOM: 'react-dom'
}

这里有更多信息 - webpack externals

这篇关于在不包含对等依赖项的情况下构建 Webpack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆