使用 webpack 创建 npm 包

Create npm package using webpack

我正在创建一个 npm 包并使用 webpack 作为 babel、eslint 等加载器。但是我假设包的最终编译版本应该只包含那个模块,没有 webpackBootstrap .

我现在的package, webpack config and source。我把它剥离成 "work".

我检查它是否正常工作的步骤:

npm install
npm run build
npm install -g .
node
var test = require('test-package');

导致此错误:

Error: Cannot find module 'test-package'
    at Function.Module._resolveFilename (module.js:337:15)
    at Function.Module._load (module.js:287:25)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at repl:1:12
    at REPLServer.defaultEval (repl.js:248:27)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:412:12)
    at emitOne (events.js:82:20)

我是 webpack 和 npm 的新手,所以如果您需要更多信息,请告诉我。

output.libraryTarget 设置为 umd。这将为您提供易于从各种模块系统(全局、AMD、CommonJS)中使用的东西。

output.library 是另一个需要设置的有用字段。这应该与您想要的全局库名称相匹配。


除此之外还有另一个问题。要使导入正常工作,需要使用 npm link。此功能在开发过程中非常有用。您可以通过 npm unlink.

还原 link