概要
rollup + babel の構成。
node_modules以下もbabelに含めたい。
polyfillもしたい。
node_modules以下のjsに対しても、それらが使うものを見て、@babel/preset-envのuseBuildIns:"usage"で自動でcorejsからimportしてほしい。
しかし無理だった。
Error: 'default' is not exported by ...
エラー
rollup-plugin-babelを使うためには、@babel/preset-envのmodules:falseの設定を入れなければいけない。
しかし、useBuildIns:"usage"を指定した瞬間、(おそらくは)modules:falseが無視され、rollup-plugin-babelが動かなくなる。
諦めてuseBuildIns:"entry"にしたら、動いたとさ。
悲しい。
versions
rollup v2.0.2
rollup-plugin-babel 4.4.0
rollup-plugin-commonjs 10.1.0
rollup-plugin-node-resolve "5.2.0
@babel/core 7.8.7
@babel/preset-env "7.8.7
core-js: 3.6.4
詳細
rollup-plugin-babelで@babel/preset-envの設定をするときは、modules:falseにしないとだめ。なぜなら、commonjsをesmoduleに変換するのはrollupのrollup-commonjsの役目であり、babelの役目ではないから。
{
"presets": [
["@babel/env", {"modules": false}]
]
}
via https://rollupjs.org/guide/en/#babel
There are a few unusual elements to this setup. First, we're setting "modules": false, otherwise Babel will convert our modules to CommonJS before Rollup gets a chance to do its thing, causing it to fail.
しかしながら、polyfillをするために、useBuiltIns:"usage"をつけてみる
{
"presets": [
["@babel/env", {
"modules": false,
"useBuiltIns": "usage",
"corejs": 3
}]
]
}
すると、Error: 'default' is not exported by ... エラーが出るようになってしまった。modules:falseをつけてないときに出るやつだ。
modules:falseが無効化されているのでは?と仮設を立てた。
こんな事を言っている人がいた
Babel can only find used methods in files it transpiles. If you need some polyfills for files Babel doesn't even see (e.g. if you are not transpiling node_modules), you'll need to manually include them (or use useBuiltIns: entry).
翻訳: Babelは、使用するメソッドを、トランスパイルするファイルでのみ見つけることができます。 Babelに表示されないファイルにポリフィルが必要な場合(たとえば、node_modulesをトランスコンパイルしていない場合)、それらを手動で含める必要があります(またはuseBuiltIns:エントリを使用します)。
うーむ、つまり node_modulesを含めるbabel設定の場合、node_modulesの先をbabel自身でトランスパイルしないと、useBuiltIns:"usage"の動作はできなく、そのオプションを付けるとmodules:falseを無視してbabelが再びcommonjs変換をしようと張り切るのではないか?
結局それが本当かどうかわからないが、useBuiltIns:"usage"を諦めて、useBuiltIns:"entry"にして、 import "core-js";
とentry fileに書いたら治った。
きっとそんな感じなんだろう。
私の設定ファイル
- rollup.config.js
- main.js
- dist/
- main.js
- node_modules/
- hoge(なにかpolyfillが必要 且つ esnext syntaxで書かれている babelにかけたいやつ)
import hoge from 'hoge'
import 'core-js'
console.log(hoge());
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import babel from 'rollup-plugin-babel'
export default {
input: 'main.js',
output: {
dir: './dist',
format: 'iife'
},
plugins: [
babel({ // .babelrcは使ってない
presets: [
[
"@babel/env",
{
modules: false,
useBuiltIns: "entry",
corejs: 3
}
]
]
}),
commonjs(),
resolve()
]
}
蛇足
私はtypescript派なので、わざわざbabelを使う理由としては、polyfillのuseBuildIns:"usage"の動作が好きだからだけだった。しかしこんな体たらくなのであれば、もはやtsc + babelの多段構成をする理由はないな。もうtscだけで終わらせてしまおう。そう思った。
ドウシテコンナニクルシイノ?