Is it possible to dynamically configure the WebPack configuration (e.g. to do Tree Shaking)?
kikar opened this issue · comments
This is a Question
Description
How can I tell webpack to do some Tree Shaking? When I import modules, I might not want the whole thing, but just a function, usually I would just execute webpack in production mode with the -p option, but doesn't seem there is a way to do this here.
You can create a webpack config that enables tree shaking (include the LoaderConfig, Uglify, etc. and enable other options as mentioned here: tree shaking and production build.
It is important that you enable production builds using the manual approach and define a separate webpack config file that includes the production stuff (see webpack.dev.js and webpack.prod.js in webpack's documentation).
Now the trick is, that you select a different webpack configuration file for different stages deployed with Serverless in your serverless.yml
:
custom:
stage: ${opt:stage}
defaultConfig: debug
webpack: ./webpack.${self:custom.stage, self:custom.defaultConfig}.conf.js
This will use webpack.debug.conf.js
as configuration if no stage option is set, otherwise it will use the stage name as part of the configuration filename.
Now you can put everything that is needed for production builds into your production configuration file.
Maybe it is even possible to create some logic within one configuration file and detect which stage is run by Serverless. But that would need some investigation first.
@kikar Where you able to successfully get it working? If yes, we should close this issue.
Can we do it better by checking the stage, and add it automatically instead of creating a new webpack config?
If stage
is prod
the add UglifyjsWebpackPlugin to the plugins?
We could expose the current serverless service configuration (aka serverless.service) into the webpack configuration. Since 2.1.0 the plugin exposes a lib module which would be the perfect target to fetch dynamic deployment information.
So it would be something like this:
// webpack.conf.js
const slsw = require('serverless-webpack');
...
const stage = slsw.lib.service.stage;
const options = slsw.lib.service.options;
...
This would open the door to access many things that might be of importance and allow a dynamic webpack configuration. stage
and options
are only examples here. The service property could be extended by other build/service properties too, that are only known at runtime.
I'll change the subject - the issue is more about dynamic configuration.
Can we do this quickly with a version 2.1.1 ?
Next will be 2.2.0 because you cannot downgrade to 2.1.0 if you use the new features like this one.