Skip to content

Commit

Permalink
allow keeping dynamic imports in selected files and apply this to fee…
Browse files Browse the repository at this point in the history
…dback module
  • Loading branch information
pieh committed Oct 17, 2022
1 parent 2215c65 commit 66dd212
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 1 deletion.
@@ -0,0 +1,54 @@
const path = require(`path`)

/**
* @typedef {import('@babel/core').NodePath} NodePath
* @typedef {import('@babel/core').PluginObj} PluginObj
* @typedef {import('@babel/core').PluginPass} PluginPass
* @typedef {import('@babel/core').types} BabelTypes
* @typedef {import('@babel/core').types.Identifier} Identifier
* @typedef {import('@babel/core').types.MemberExpression} MemberExpression
*/

/**
* @typedef {Object} IPluginOptions
* @property {Array<string>} keepDynamicImports
*/

/**
*
* @param {{ types: BabelTypes }} _unused
* @param {Partial<IPluginOptions>} opts
* @returns {PluginObj}
*/
module.exports = function keepDynamicImports(
_unused,
opts
) {
if (!opts.keepDynamicImports) {
throw new Error(`keepDynamicImports option needs to be set`)
} else if (!Array.isArray(opts.keepDynamicImports)) {
throw new Error(`keepDynamicImports option needs to be an array`)
}

const absolutePaths = opts.keepDynamicImports.map(p => path.resolve(p))

return {
name: `babel-transform-mark-to-keep-dynamic-import`,
visitor: {
Program() {
const filename = this.file?.opts?.filename
if (!filename) {
return
}

if (absolutePaths.includes(filename)) {
// this is big hack - it relies on some babel plugins internal to basically
// do early return ( https://github.com/babel/babel/blob/3526b79c87863052f1c61ec0c49c0fc287ba32e6/packages/babel-plugin-transform-modules-commonjs/src/index.ts#L174 )
// on top of that `BabelFile` doesn't expose delete for the metadata,
// so we reach into internal `_map` to delete it
this.file._map.delete("@babel/plugin-proposal-dynamic-import")
}
}
},
}
}
7 changes: 7 additions & 0 deletions packages/babel-preset-gatsby-package/lib/index.js
Expand Up @@ -7,6 +7,7 @@ function preset(context, options = {}) {
nodeVersion = `18.0.0`,
esm = false,
availableCompilerFlags = [`GATSBY_MAJOR`],
keepDynamicImports = null
} = options
const {
NODE_ENV,
Expand Down Expand Up @@ -86,6 +87,12 @@ function preset(context, options = {}) {
},
],
r(`babel-plugin-lodash`),
Array.isArray(keepDynamicImports) && keepDynamicImports.length > 0 && [
r(`./babel-trasnform-mark-to-keep-dynamic-import`),
{
keepDynamicImports,
},
]
].filter(Boolean),
overrides: [
{
Expand Down
4 changes: 3 additions & 1 deletion packages/gatsby/babel.config.js
Expand Up @@ -3,5 +3,7 @@
// Ref: https://github.com/babel/babel/pull/7358
module.exports = {
sourceMaps: true,
presets: [["babel-preset-gatsby-package"]],
presets: [["babel-preset-gatsby-package", {
keepDynamicImports: [`./src/utils/feedback.ts`]
}]],
}

0 comments on commit 66dd212

Please sign in to comment.