I have a library that can be used with both node.js and the browser. I am using CommonJS then publishing for the web version using webpack. My code looks like this:
// For browsers use XHR adapter if (typeof window !== 'undefined') { // This adapter uses browser's XMLHttpRequest require('./adapters/xhr'); } // For node use HTTP adapter else if (typeof process !== 'undefined') { // This adapter uses node's `http` require('./adapters/http'); }
The problem I am encountering is that when I run webpack (browserify would do the same) the generated output includes http
along with all it's dependencies. This results in a HUGE file which is not optimal for browser performance.
My question is how can I exclude the node code path when running a module bundler? I solved this temporarily by using webpack's externals and just returning undefined when including './adapters/http'
. This doesn't solve the use case where other developers depend on my library using CommonJS. Their build will end up with the same problem unless they use similar exclude config.
I've looked at using envify, just wondering if there is another/better solution.
Thanks!
Browserify solves the problems of having too many JS files referenced in your HTML, inability to use Node modules in the browser, and inability to reference your own modules in your own code. Watchify streamlines the process of bundling your files and will make a change every time you change a JS file in your project.
Webpack is a module bundler. It takes disparate dependencies, creates modules for them and bundles the entire network up into manageable output files. This is especially useful for Single Page Applications (SPAs), which is the defacto standard for Web Applications today.
Browserify is used to read the strings available in the static files, and the node uses the native read file function, whereas the webpack uses a common object to overload the needed function and applies a distinct loader to load the files, and its names should have a suitable pattern.
Webpack builds a dependency graph used internally Now all modules that are used in your app are included in the dependency graph. Your project have many installed dependencies in the node_modules folder that should not be included in your client-side JavaScript production bundle.
You may use IgnorePlugin
for Webpack. If you are using a webpack.config.js file, use it like this:
var webpack = require('webpack') var ignore = new webpack.IgnorePlugin(/^(canvas|mongoose|react)$/) module.exports = { //other options goes here plugins: [ignore] }
To push it further, you may use some flags like process.env.NODE_ENV
to control the regex filter of IgnorePlugin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With