我在捆绑同态/通用应用程序时遇到了问题。出于某种原因,treeshaking和uglify都完全忽略了MongoDB没有在任何代码路径中使用的事实,并将其包含到我的浏览器包中,这使得它非常大(1.3 MB)并且不可用(因为本机Node模块)。它应该省略所有MongoDB相关的代码,因为它是未使用的。它甚至可以正确地从bundle中删除无用的代码分支,但是MongoDB依赖项仍然存在,未使用。
My entrypoint (index.js):
import { TestService } from "../../services/TestService";
import { container, services } from "../../ioc";
const test = container.get("test");
test.retrieveTestMessage.then((result) => console.log(result));
ioc.js:
// omitted Inversify setup
import { TestService } from "./services/TestService";
if (DEPLOYMENT_NODE == true) // DefinePlugin sets this to false; only the 'else' branch is correctly included in the bundle
{
container.bind("test").to(TestService);
}
else
{
container.bind("test").toConstantValue(createClient(API_URL, "test"));
}
TestService.js:
import { injectable } from "inversify";
import { MongoClient } from "mongodb";
@injectable()
export class TestService
{
public async retrieveTestMessage()
{
if (DEPLOYMENT_NODE == true)
{
// omitted MongoClient usage
}
}
}
createClient功能:
export function createClient(url, service)
{
const client = new Proxy(
{},
{
get: (target, property, receiver) => async (...params) => fetch(url, { headers: new Headers({ "Content-Type": "application/json" }), method: "POST", body: JSON.stringify({ id: 0, service: service, method: property, parameters: params }) })
}
);
return client;
}
我试图在我的Webpack配置中使用webpack.IgnorePlugin(/mongodb/)
,它真的不包括MongoDB,但捆绑失败,"MongoDB模块未找到"错误,即使它根本不使用。
如果有人有任何其他建议,我非常感谢。谢谢。
编辑:我使用最新的Webpack 2测试版,并在我的babel配置中保留ES6模块。
if
条件下的显式要求应该成立
import { injectable } from "inversify";
@injectable()
export class TestService
{
public async retrieveTestMessage()
{
if (DEPLOYMENT_NODE == true)
{
const { MongoClient } = require("mongodb");
// omitted MongoClient usage
}
}
}