javascript Webpack 条件要求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31249976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:32:46  来源:igfitidea点击:

Webpack conditional require

javascriptwebpackleveldbisomorphic-javascript

提问by vardump

I'm writing an isomorphic Key Value Store with webpack.

我正在用 webpack 编写一个同构的键值存储。

This is currently my approach to load the libraries, which obviously doesn't work, because webpack wants to resolve both require. Whats' the right approach?

这是我目前加载库的方法,这显然不起作用,因为 webpack 想要同时解析require. 什么是正确的方法?

var db = null;

if (typeof window === 'undefined') {
    // node context
    db = require('level');
} else {
    // browser context
    db = require('gazel');
}

I know, that you can provide a targetto webpack. But I have no idea how to use that.

我知道,您可以为webpack提供目标。但我不知道如何使用它。

Thanks!

谢谢!

采纳答案by Juho Veps?l?inen

I think resolve.aliaswould work for you. You would set dbmodule to point at levelor gazeldepending on which build you are creating.

我认为resolve.alias对你有用。您可以将db模块设置为指向levelgazel取决于您正在创建的构建。

回答by Lonelydatum

webpack.config.js

webpack.config.js

module.exports = {
plugins: [
    new webpack.DefinePlugin({
        "process.env": {
            BROWSER: JSON.stringify(true)
        }
    })
]}

your-universal.js

你的universal.js

var db = null;
if (!process.env.BROWSER) {
    // node context
    db = require('level');
} else {
    // browser context
    db = require('gazel');
}