Javascript 在Webpack 4中创建节点库

Javascript 在Webpack 4中创建节点库,javascript,node.js,webpack,configuration,dependencies,Javascript,Node.js,Webpack,Configuration,Dependencies,我正在尝试使用webpack和babel创建节点库,以便使用ES2017。一切正常,但问题是输出文件的大小与原始文件大小相比太大。我的测试库非常简单,因为唯一的依赖项是mongodb包。以下是该库的完整代码: import crypto from "crypto"; import { MongoClient } from "mongodb"; let client = null; let db = null; /** * Connects to database using info de

我正在尝试使用webpack和babel创建节点库,以便使用ES2017。一切正常,但问题是输出文件的大小与原始文件大小相比太大。我的测试库非常简单,因为唯一的依赖项是mongodb包。以下是该库的完整代码:

import crypto from "crypto";
import { MongoClient } from "mongodb";

let client = null;
let db = null;

/**
 * Connects to database using info defined in environment variables (MONGO_URL,
 * MONGO_DATABASE, MONGO_SSL, MONGO_SSL_VALIDATE).
 *
 * @async
 * @function connect
 */
const connect = async () => {
  if (!client) {
    // Connect to MongoDB server.
    client = await MongoClient.connect(process.env.MONGO_URL, {
      ssl: process.env.MONGO_SSL || false,
      sslValidate: process.env.MONGO_SSL_VALIDATE || false
    });
    // Get database.
    db = client.db(process.env.MONGO_DATABASE);
  }
};

/**
 * Disconnects from database.
 *
 * @async
 * @function disconnect
 */
const disconnect = async () => {
  if (client) {
    await client.close();
    client = null;
    db = null;
  }
};

/**
 * Disconnects from database.
 *
 * @function getDatabase
 * @return {Db} MongoDB instance of the Db class.
 */
const getDatabase = () => {
  if (!client) {
    throw new Error("Not connected to database");
  }
  return db;
};

/**
 * Gets collection.
 *
 * @function getCollection
 * @return {Collection<TSchema>} MongoDB instance of the Collection class.
 */
const getCollection = collectionName => {
  if (!client) {
    throw new Error("Not connected to database");
  }
  // Get collection.
  return db.collection(collectionName);
};

/**
 * Generates Mongo ID string compatible with Meteor Mongo IDs.
 *
 * @function generateId
 * @param {number} charsCount - Length of the Mongo ID string.
 * @return {string} Mongo ID string compatible with Meteor Mongo ID.
 */
const generateId = (charsCount = 17) => {
  const CHARS = "23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz";
  const digits = [];
  for (let i = 0; i < charsCount; i++) {
    let bytes;
    try {
      bytes = crypto.randomBytes(4);
    } catch (e) {
      bytes = crypto.pseudoRandomBytes(4);
    }
    const hexString = bytes.toString("hex").substring(0, 8);
    const fraction = parseInt(hexString, 16) * 2.3283064365386963e-10;
    const index = Math.floor(fraction * CHARS.length);
    digits[i] = CHARS.substr(index, 1);
  }
  return digits.join("");
};

export { connect, disconnect, getDatabase, getCollection, generateId };
输出文件大小为19 KB。。。它包含了很多我猜是不必要的多边形填充。为什么即使我告诉webpack我正在创建库,它也会将它们包含在输出文件中


在.map文件中,我可以看到如下内容:webpack:///./node_modules/core-js/library/modules/_has.js 或webpack:///./node_modules/@babel/runtime/core js/promise.js

如果您的库在节点环境中使用,您可能不想使用webpack。仅仅通过babel运行所有文件就足够了

Webpack旨在将任何模块语法中的依赖关系树转换为单个捆绑包,以便在web浏览器中使用


在您的情况下,唯一的目标是将一种语言级别转换为另一种语言级别,这正是巴贝尔所做的。提供了有关如何使用babel cli传输代码的足够信息。

我发现了一个问题。大文件大小是由babel插件Transfile运行时引起的。实际上,它不需要插件的特性,而是将所有代码放在文件中。我不知道它为什么这么做。所以,当我知道是什么原因导致它时,我仍然不知道如何修复它。

是的,我知道。我以前只使用Babel,但它在我的用例中不起作用。事实上,我只是展示了我正在创建的更大工具的一个简单部分。我正在创建一个用于创建节点包的工具。我正在为一个项目创建很多包,我已经厌倦了用webpack配置每个包,很难让配置保持最新。我需要webpack对构建过程有更多的控制。你能展示一个babel配置示例吗?非常感谢。
const path = require("path");
const paths = require("../lib/paths");

const externals = Object.keys(
  require(path.resolve(paths.pkg, "package.json")).dependencies || {}
);

module.exports = {
  mode: "production",
  entry: path.resolve(paths.src, "index.js"),
  output: {
    libraryTarget: "commonjs",
    path: paths.dist,
    filename: "index.js"
  },
  node: {
    __filename: true,
    __dirname: true
  },
  devtool: "source-map",
  target: "node",
  externals: externals,
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: paths.loaders.babel,
          options: {
            plugins: [
              paths.plugins.proposalClassProperties,
              paths.plugins.proposalObjectRestSpread,
              paths.plugins.transformRuntime
            ],
            presets: [[paths.presets.env, { targets: { node: "6.10" } }]]
          }
        },
        exclude: /node_modules/
      }
    ]
  }
};