Bundle JS with rollup and Babel for use in IE11

风流意气都作罢 提交于 2021-01-23 11:09:10

问题


I try to bundle two JavaScript modules, so that the resulting code works in IE11. For this I have setup a yarn/npm project which uses rollup.js for bundling and Babel for transpiling. Everything works fine until I add the (non-dev) dependency core-js.

Here the details:

1 Setup before adding core-js

JS files

  • src/main.js
  • src/utils.js

Config files

package.json

{
  "name": "rollup_for_ie",
  "devDependencies": {
    "@babel/core": "^7.11.1",
    "@babel/preset-env": "^7.11.0",
    "@rollup/plugin-babel": "^5.2.0",
    "@rollup/plugin-node-resolve": "^9.0.0",
    "rollup": "^2.24.0"
  },
}

rollup.config.js

import resolve from '@rollup/plugin-node-resolve';
import babel from '@rollup/plugin-babel';

export default {
  input: 'src/main.js',
    output: {
        file: 'dist/main.js',
        format: 'iife'
    },
  plugins: [
    resolve({
      browser: true
    }),
    babel({
        exclude: "node_modules/**", // only transpile our source code
        babelHelpers: 'bundled'
    })
  ]
};

babel.config.js

module.exports = {
  presets: [
    [
      "@babel/preset-env",
      {
        targets: {
          browsers: "> 0.5%, ie >= 11"
        },
        modules: false,
        spec: true,
        useBuiltIns: "usage",
        forceAllTransforms: true,
        corejs: 3
      }
    ]
  ],
};

When I run rollup -c I get warnings about unresolved dependencies, but a bundled file dist/main.js with the (used) stuff from the src directory is generated. The resulting file works even in modern browsers like Chrome. So far so good.

Problems after adding core-js

However the bundled file is not yet IE11 ready: In IE I get errors like Object doesn't support property or method 'getOwnPropertySymbols'. So the polyfills from core-js need to be added.

For this I install core-js as a prod dependency. Now rollup -c doesn't give me warnings - but the resulting dist/main.js begins like

(function (exports) {
  'use strict';

  var $ = require('../internals/export');
.
.
.

which as a script can not neither Chrome nor IE execute! It looks like that somehow the presence of the core-js library throws the rollup bundler off.

How can I fix my setup so that the resulting dist/main.js works as non-module script in Chrome and IE11?


回答1:


I think as you enabled the option useBuiltIns: "usage" which means it will append code from corejs into your module files which is written with cjs style. So you have to add this plugin @rollup/plugin-commonjs to convert back to esm, then it will work:

import commonjs from '@rollup/plugin-commonjs';

export default {
  // ...
  plugins: [
    // ...
    commonjs(),
  ]    
};


来源:https://stackoverflow.com/questions/63407950/bundle-js-with-rollup-and-babel-for-use-in-ie11

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