在Webpack 4中创建节点库

时间:2018-03-13 20:21:30

标签: 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 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 };

这是我的webpack.config.js

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/
      }
    ]
  }
};

输出文件大小为19 KB ...它包含了很多我认为不需要的polyfill。为什么地狱webpack将它们包含在输出文件中,即使我告诉它我正在创建库。

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

2 个答案:

答案 0 :(得分:0)

如果您的库在Node环境中使用,则可能不希望使用webpack。只需通过babel运行所有文件就足够了。

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

在你的情况下,唯一的目标是将一个语言级别转换为另一个语言级别,这正是babel所做的。 babel docs提供了有关如何使用babel-cli来转换代码的足够信息。

答案 1 :(得分:0)

我发现了一个问题。文件大小由babel-plugin-transpile-runtime引起。实际上,它不是要求插件中的功能,而是将所有代码放在文件中。我不知道为什么会这样做。因此,我知道是什么导致它,我仍然不知道如何解决它。