How do I use babel's `useBuiltIns: 'usage'` option on the vendors bundle?

给你一囗甜甜゛ 提交于 2019-12-03 00:49:21

Babel by default assumes that files it processes are ES modules (using import and export). If you are running Babel on things in node_modules (which are likely CommonJS modules), you'll need to either tell Babel to process all node_modules as scripts, or tell Babel to guess the type based on the presence of import and export. Guessing is easiest, so you can add

sourceType: "unambiguous"

and also tell Babel not to run the usage transform on core-js itself with

  ignore: [
    /\/core-js/,
  ],

because otherwise the usage transform will actually be inserting references to core-js into itself causing dependency cycles.

So in your top-level Babel configuration, you'd do e.g.

{
  ignore: [
    /\/core-js/,
  ],
  sourceType: "unambiguous",
  presets: [
    ['@babel/preset-env', { modules: false, useBuiltIns: 'usage' }],
  ],
}

If you wanted to be extra specific about it, you could also do

{
  ignore: [
    /\/core-js/,
  ],
  presets: [
    ['@babel/preset-env', { modules: false, useBuiltIns: 'usage' }],
  ],
  overrides: [{
    test: "./node_modules",
    sourceType: "unambiguous",
  }],
}

to only set the flag for files inside node_modules, but there is likely not much to gain by doing that.

As for why this fixes that error, the issue is that, if Babel thinks something is an ES module, it will insert import statements. If you insert import statements into a file that also uses CommonJS things like module.exports, it means the file would now be using both module systems in the same file, which is a big issue and causes the errors you are seeing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!