简体   繁体   中英

webpack & using node modules in an isomorphic package

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?

First option

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.

Second way

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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