70 %
Chris Biscardi

Using Amplify with ESM based sites

Amplify doesn't work by default on ESM-based sites because it expects you to webpack it.

Building a library using this import set

JS
export { default as Amplify, Hub, Auth } from "aws-amplify";

and this webpack config

JS
const path = require("path");
const EsmWebpackPlugin = require("@purtuga/esm-webpack-plugin");
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "./dist"),
filename: "amplify-esm-bundle.js",
globalObject: "this",
library: "AMPLIFY",
libraryTarget: "umd"
},
externals: {},
// plugins: [new EsmWebpackPlugin()],
module: {
// rules: [
// {
// test: /\.(js)$/,
// exclude: /(node_modules|bower_components)/,
// use: 'babel-loader'
// }
// ]
}
};

Results in 1.1mb of JS transferred over the network with a total size of 12.1 MB. yikes.

Using webpack --production brings it down to a lowly 404k. Still many times the size of everything else on my site combined.

Under the [Advanced Workflows tab (https://docs.amplify.aws/lib/auth/advanced/q/platform/js#using-modular-imports) in the #using-modular-imports heading of the amplify auth documentation, we can see that there's a completely separate package we should be using.

JS
export { default as Auth } from "@aws-amplify/auth";

With that, we get 281k which to be honest I'm happy with and feel bad about.

Unfortunately I need the API package as well

JS
export { default as Auth } from "@aws-amplify/auth";
export { default as API, graphqlOperation } from "@aws-amplify/api";

so my bundle size is 433kb. :scream: