diff --git a/index.js b/index.js index eb68a22..73160b6 100644 --- a/index.js +++ b/index.js @@ -7,6 +7,7 @@ const compile = require('./lib/compile'); const cleanup = require('./lib/cleanup'); const run = require('./lib/run'); const serve = require('./lib/serve'); +const packExternalModules = require('./lib/packExternalModules') class ServerlessWebpack { constructor(serverless, options) { @@ -19,7 +20,8 @@ class ServerlessWebpack { compile, cleanup, run, - serve + serve, + packExternalModules ); this.commands = { @@ -28,6 +30,7 @@ class ServerlessWebpack { lifecycleEvents: [ 'validate', 'compile', + 'packExternalModules', ], options: { out: { @@ -89,7 +92,8 @@ class ServerlessWebpack { this.hooks = { 'before:deploy:createDeploymentArtifacts': () => BbPromise.bind(this) .then(this.validate) - .then(this.compile), + .then(this.compile) + .then(this.packExternalModules), 'after:deploy:createDeploymentArtifacts': () => BbPromise.bind(this) .then(this.cleanup), @@ -100,6 +104,9 @@ class ServerlessWebpack { 'webpack:compile': () => BbPromise.bind(this) .then(this.compile), + 'webpack:packExternalModules': () => BbPromise.bind(this) + .then(this.packExternalModules), + 'webpack:invoke:invoke': () => BbPromise.bind(this) .then(this.validate) .then(this.compile) diff --git a/lib/packExternalModules.js b/lib/packExternalModules.js new file mode 100644 index 0000000..47ce647 --- /dev/null +++ b/lib/packExternalModules.js @@ -0,0 +1,44 @@ +'use strict'; + +const BbPromise = require('bluebird'); +const webpack = require('webpack'); +const fs = require('fs'); +const path = require('path'); +const npm = require('npm-programmatic'); + +module.exports = { + packExternalModules() { + + this.serverless.cli.log(this.webpackOutputPath); + + this.serverless.cli.log(JSON.stringify(this.webpackConfig.externals)); + + const externals = this.webpackConfig.externals; + + return BbPromise.resolve().then(() => { + if (!externals || externals.length === 0) { + return; + } + + this.serverless.cli.log('packing external modules'); + + const tmpPackageJson = path.join(this.webpackOutputPath, 'package.json'); + + // create a temp package.json in dist directory so that we can install the dependencies later. + fs.writeFileSync(tmpPackageJson, "{}"); + + return new BbPromise((resolve, reject) => { + npm.install(externals, { + cwd: this.webpackOutputPath, + save: false + }).then(() => { + fs.unlink(tmpPackageJson); + resolve() + }).catch(e => { + fs.unlink(tmpPackageJson); + reject(e); + }) + }) + }) + }, +}; diff --git a/package.json b/package.json index dae65b0..2995ecb 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,7 @@ "body-parser": "^1.15.2", "express": "^4.14.0", "fs-extra": "^0.26.7", + "npm-programmatic": "0.0.5", "webpack": "^1.13.1" }, "devDependencies": {