问题
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