Create npm package using webpack

2019-02-06 00:15发布

问题:

I'm creating an npm package and using webpack for loader like babel, eslint etc.. However I'm under assumption that final compiled version of the package should only contain that one module, without webpackBootstrap.

My current package, webpack config and source. I stripped it down to just make it "work".

Steps I took to check if it's working:

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

Resulting in this error:

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)

I'm new to webpack and npm so let me know if you need any more information.

回答1:

Set output.libraryTarget to umd. That will give you something that's easy to consume from various module systems (global, AMD, CommonJS).

output.library is another useful field to set. That should match the name of your library global you want.


There was another problem beyond this. To make the import work npm link needed be used. This feature is highly useful during development. You can revert a link through npm unlink.