Search code examples
javascriptnode.jswebpackbabeljsbabel-loader

Using local npm libraries with es6, babel, and webpack


I'm running into an issue that appears to be due to my lack of understanding with webpack. I have created a file structure that looks like this:

|-serverless-cloud-functions
||-my-local-libs
|||-twilioClient
||-service1
||-service2

twilioClient is a library that I made, that needs to be included in service1 and service2. Because of limitations with the serverless framework, you can not bundle files outside of the service, so the only option (I think) is to use a npm install ../my-local-libs/twilioClient from inside a service folder. This works for installing the module, but now it resides in node_modules. Currently, I am using webpack and babel as well.

I believe my root issue is that my webpack config looks like this:

const slsw = require("serverless-webpack");
const nodeExternals = require("webpack-node-externals");

module.exports = {
    entry: slsw.lib.entries,
    target: "node",

    externals: [nodeExternals()],

    module: {
        rules: [
            {
                test: /\.js$/,
                loader: "babel-loader",
                exclude: /node_modules/
            }
        ]
    }
};

Which excludes my es6 twilioClient lib, because it is in the node_modules folder.

I saw a couple people suggest that this was the way to accomplish 'exclude everything in node modules besides twilioClient':

module.exports = {
    entry: slsw.lib.entries,
    target: "node",

    externals: [nodeExternals()],

    module: {
        rules: [
            {
                test: /\.js$/,
                loader: "babel-loader",
                exclude: /node_modules\/(?!(twilioClient))/
            }
        ]
    }
};

But this did not work in my case. Any help is greatly appreciated.


Solution

  • Instead of trying to exclude twilioClient, you could use Babel to compile it separately. Something like this (in the twilioClient directory):

    npx babel src --out-dir lib
    

    In twilioClient/package.json, you could then set main to lib/index.js instead of src/index.js so that importing scripts will get the compiled version:

    "main": "lib/index.js",
    

    Then instead of hosting twilioClient alongside service1 and service2, you could just push it to github, and install it in each client using npm:

    npm install --save http://github.com/your_github_username/twilioclient.git

    Now you can use twilioClient as if it were any other npm dependency.