citrus327 / issue-blog-record

2 stars 2 forks source link

rollup打包 _export is not defined问题解决方案 #40

Closed citrus327 closed 2 years ago

citrus327 commented 2 years ago

rollup打包 _export is not defined问题解决方案

Rollup 配置

import { babel } from "@rollup/plugin-babel";
import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";
import url from "@rollup/plugin-url";
import external from "rollup-plugin-peer-deps-external";
import postcss from "rollup-plugin-postcss";
import typescript from "rollup-plugin-typescript";
import pkg from "./package.json";

const config = {
  input: "src/index.ts",
  output: [
    {
      file: pkg.main,
      format: "cjs",
      exports: "named",
    },
    {
      file: pkg.module,
      format: "es",
      exports: "named",
    },
  ],
  plugins: [
    resolve(),
    commonjs(),
    postcss({
      plugins: [],
      minimize: true,
    }),
    external({
      includeDependencies: false,
    }),
    babel({
      babelHelpers: "bundled",
      presets: [
        [
          "@babel/preset-env",
          {
            useBuiltIns: "usage",
            corejs: 3,
          },
        ],
      ],
    }),
    url(),
    typescript({ tsconfig: "./tsconfig.json" }),
  ],
};

export default config;

问题

报出 $$1w is not defined,实际查证是$$1w指向了_export这个方法。而_export的定义在最下方。

原因

根据以下Issue

  1. https://github.com/rollup/plugins/issues/466
  2. https://github.com/rollup/rollup/issues/3802

原因是当打包dependencies时,core-js本身会被babel再解析一遍,造成循环引用。

Quote:

You need to exclude core-js from babel or @babel/preset-env with useBuiltins: 'usage' will create a circular reference trying to process core-js itself:

解决方案

  1. external插件配置includeDependencies: true, 产物不打包core-js
  2. babel插件exclude core-js

结果

external({
  includeDependencies: false,
}),
babel({
  babelHelpers: "bundled",
  exclude: [/core-js/],
  presets: [
    [
      "@babel/preset-env",
      {
        useBuiltIns: "usage",
        corejs: 3,
      },
    ],
  ],
})

或者

external({
  includeDependencies: true,
}),
babel({
  babelHelpers: "bundled",
  presets: [
    [
      "@babel/preset-env",
      {
        useBuiltIns: "usage",
        corejs: 3,
      },
    ],
  ],
})