简体   繁体   English

如何捆绑模块而不依赖于发布npm包

[英]How to bundle module without dependencies for publishing npm package

Recently, I developed a React component and want to publish it. 最近,我开发了一个React组件并希望发布它。

In this package, 在这个包中,

"dependencies": {
  "react": "^0.14.6",
  "react-dom": "^0.14.6",
  "react-timer-mixin": "^0.13.3"
}

When I build the package by webpack command, I will get a bundle containing react, react-dom and react-timer-mixin . 当我通过webpack命令构建包时,我将得到一个包含react, react-dom and react-timer-mixin
It seems wrong for this practice... 这种做法似乎有误......

Thus, my question is how to build package without dependencies for publishing. 因此,我的问题是如何构建没有依赖关系的包进行发布。

*I think the chuck-vendor method to separate main bundle and dependencies is for multiple bundle file. *我认为用于分离主bundle和依赖关系的chuck-vendor方法是针对多个bundle文件的。 But my requirement is for building the lib. 但我的要求是构建lib。

If you are building a library, you need to register these dependencies as externals . 如果要构建库,则需要将这些依赖项注册为外部

To summarise, just add the externals property in your webpack config and set it to an array containing the names (string) of the modules to exclude. 总而言之,只需在webpack配置中添加externals属性,并将其设置为包含要排除的模块的名称(字符串)的数组。

A more complex case could require you to specify how should be imported your dependencies in function of the import system. 更复杂的情况可能需要您指定如何在导入系统的功能中导入依赖项。 You can achieve this using an object. 您可以使用对象实现此目的。

Here is the official example : 这是官方的例子

module.exports = {
    output: {
        libraryTarget: "umd"
    },
    externals: [
        "add",
        {
            "subtract": {
                root: "subtract",
                commonjs2: "./subtract",
                commonjs: ["./math", "subtract"],
                amd: "subtract"
            }
        }
    ]
}

See here for more information about library and externals . 有关库和外部的更多信息,请参见此处

If you are using ES 2015 and babel 6, you may also encounter an issue with the export of the library being a module object instead of what you want (eg your component). 如果您使用的是ES 2015和babel 6,您可能会遇到一个问题,即导出库是模块对象而不是您想要的(例如您的组件)。 Have a look at this question to solve it. 看看这个问题来解决它。

Perhaps you should use peerDependencies instead. 也许您应该使用peerDependencies Then you can build without webpack for publishing. 然后你可以构建没有webpack进行发布。 If you use ES6, all you need is a babel transpilation step. 如果你使用ES6,你所需要的只是一个babel蒸腾步骤。

Something like this is often enough 这样的事情经常就足够了

babel ./src -d ./lib

Peer dependencies will let npm know the project using your package should have those dependencies installed. 对等依赖项将让npm知道使用您的包的项目应该安装这些依赖项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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