如何使用webpack构建一个独立的库,以便可以导入/需要它?

时间:2018-02-21 21:22:41

标签: javascript node.js webpack ecmascript-6 babeljs

我写了一个做某事的库(duh)。我的客户端需要在AWS上运行代码作为无服务器功能,但我的库使用的是在运行AWS的旧版本Node.js上不支持的ES6。

所以我想构建我的代码,以便它只导出执行我们需要的功能,并且可以在其他脚本中require d。 Webpack构建正常,代码按照预期运行,但不会从打包代码中导出任何内容。

这是MCVE:

webpack.config.js

const path = require('path');
var nodeExternals = require('webpack-node-externals');
module.exports = {
    entry: ['babel-polyfill', './serverless_function.js'],
    output: {
        path: path.resolve('dist'),
        filename: 'serverless_lib.js',
        library: 'ServerlessTest',
    },
    module: {
        loaders: [
            { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
            { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ }
        ]
    },
    target: 'node',
    externals: [nodeExternals()]
}

serverless_function.js

这个应该是打包的。它包含并使用我库中的代码来执行应在AWS上完成的任务。在这个例子中,它只读取一个文件并将其返回。

结果应打包并放入dist/serverless_library.js,如webpack.config.js中所述。

require("babel-core/register");
const fs = require("fs");

function ReadTestFile() {
    return new Promise(function (res, rej) {
        fs.readFile("test.txt", function (err, data) {
            if (err)
                rej(err);
            else
                res(data);
        })
    });
}

async function testFunction(event, context, callback) {
    const response = {
        statusCode: 200,
        headers: {

            "Content-Type": "text/plain",
            "Content-Disposition": "inline; filename=\"test.txt\""
        },
        body: await ReadTestFile()
    };
    return callback(null, response);
}
console.log("Exporting function: ", testFunction);
export default testFunction;

.babelrc

{
  "presets": [ "es2015", "stage-0" ],
  "plugins": [
    [
      "transform-runtime",
      {
        "polyfill": false,
        "regenerator": true
      }
    ]
  ]
}

server.js

这是一个测试脚本,应该能够加载打包库并使用它。

'use strict';
var http = require('http');
var port = process.env.PORT || 1337;

const SERVERLESS = require("./dist/serverless_lib");
// The serverless should be a function, since that's what I export in serverless_function.js
if (typeof SERVERLESS != "function") {
    throw new Error("Webpack still didn't pack the export correctly!");
}

http.createServer(async function (req, res) {
    console.log(req.rawHeaders);

    res.writeHead(200, { 'Content-Type': 'text/plain' });

    SERVERLESS(null, null, (unused, response) => {
        res.end(new Buffer(response.body));
    });
}).listen(port);

我创建了一个包含所有内容的github仓库:https://github.com/Darker/webpack-library-example

我希望这个例子足够了。

0 个答案:

没有答案
相关问题