Reputation: 1197
I am building an isomorphic package where I am using a flag in various files to detect if we are in the browser or in node. If in node, I require an internal package ie if (isNode) { require("/.nodeStuff) }
that has as one of its dependencies the fs
module. However, webpack does not like this for obvious reasons. Is there any type of module-based webpack config file that I can configure to ignore the node-based requires entirely so that this does not happen?
Upvotes: 0
Views: 365
Reputation: 4143
As stated in the docs, in order to solve this isomorphic problem you could simply run two builds, one for each environment (node and web). The guide can be found here. Keep in mind you should probably mock any built ins in the clientConfig
by adding this block
node: { fs: 'empty',//any other node lib used }
. That way webpack will not complain and since your client code will be under the !IS_NODE
condition the empty fs
will never be used.
Although this is a solid solution you end up with 2 bundles and you need of course a way to distribute them to the correct platform each time.
This solution is based on the not very well known __non_webpack_require__
function. This is a webpack specific function that will instruct the parser to avoid bundling this module that is being requested and assume that a global require
function is available. This is exactly what happens while running in node instead of a browser.
//webpack.config.js
{
mode: "development",
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
node: false
}
// nodeStuff.js
const fs = __non_webpack_require__('fs'); //this will be transformed to require('fs')
fs.writeFileSync('some','thing)
That way since nodeStuff.js
will only be required under the IS_NODE
condition, the native require
will be available.
I would suggest to use __non_webpack_require__
on native libraries only, that you are sure that will be available!
Upvotes: 1