Skip to content

Instantly share code, notes, and snippets.

@hjzheng
Last active October 14, 2022 06:02
Show Gist options
  • Save hjzheng/969c47661f4636d15a0234b3ce1edc72 to your computer and use it in GitHub Desktop.
Save hjzheng/969c47661f4636d15a0234b3ce1edc72 to your computer and use it in GitHub Desktop.
function addComments(arg, name) {
// 当参数前的注释不存在的情况, 加入 webpackChunkName 注释
if (!arg.leadingComments) {
arg.leadingComments = [
{
type: 'CommentBlock',
value: ` webpackChunkName: '${name}' `,
},
]
}
}
module.exports = function(babel) {
const { types: t } = babel
return {
name: 'ast-transform', // not required
visitor: {
CallExpression: function(path) {
const { node } = path
if (t.isImport(node.callee)) {
const arg0 = node.arguments[0]
const name = arg0.value
addComments(arg0, name.replace(/.*\/(.*)$/, '$1'))
}
},
},
}
}
@hjzheng
Copy link
Author

hjzheng commented Jul 26, 2019

try it on https://astexplorer.net/

use it in .babelrc

{
  "plugins": [
    "./some_path/plugin-babel-import-chunkname.js"
  ]
}

transpile

import('./page/About')

to

import(/*  webpackChunkName: 'About'  */ './page/About')

@entr
Copy link

entr commented Mar 15, 2020

Doesn't seem to work with await import(). Do you have any clue why?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment