rollup外部引用(external)antd,报require is not defined,不加外部引用没问题?

新手上路,请多包涵
import htmlTemplate from "rollup-plugin-generate-html-template";
import typescript from "rollup-plugin-typescript2";
import clear from "rollup-plugin-clear";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import { babel } from "@rollup/plugin-babel";
import { terser } from "rollup-plugin-terser";
import serve from "rollup-plugin-serve";
import livereload from "rollup-plugin-livereload";
import replace from "rollup-plugin-replace";

const env = process.env.NODE_ENV;

export default {
  input: "./src/index.tsx",
  output: {
    file: `dist/bundle.${env === "production" ? "production" : "min"}.js`,
    format: "cjs",
  },
  // 自定义警告事件,这里由于会报THIS_IS_UNDEFINED警告,这里手动过滤掉
  onwarn: function (warning) {
    if (warning.code === "THIS_IS_UNDEFINED") {
      return;
    }
  },
  // 这跟external 是配套使用的,指明global.antd即是外部依赖antd
  //   globals: {
  //     antd: "antd",
  //   },
  // 将模块视为外部模块
  external: ["antd"],
  plugins: [
    // 使在项目中用到的node_modules能够被正常加载
    nodeResolve(),
    // 会自动读取tsconfig
    // 使在项目中import的ES模块可以被正常加载
    commonjs(),
    typescript(),
    htmlTemplate({
      template: "./public/index.html",
      target: "index.html",
    }),
    // 自动清理包
    clear({
      targets: ["dist"],
    }),
    babel({
      exclude: "./node_modules/**",
      runtimeHelpers: true,
    }),
    // 会自动读取babel的配置文件
    // 压缩代码
    env === "production" && terser(),
    serve({
      // open: true,
      port: 8080,
      contentBase: "dist",
    }),
    livereload(),
    // react中使用的process,而process是node环境的变量,浏览器中是没有的,所以需要替换
    // 这里必须加replace,参考https://github.com/rollup/rollup/issues/487
    replace({
      preventAssignment: true,
      "process.env.NODE_ENV": JSON.stringify(env)
    }),
  ],
};

这个整个配置文件,其中@rollup/plugin-commonjs@rollup/plugin-commonjs都是有的,只要配置项加上external: ["antd"]就会报以下错误
image.png,不加的话就没有问题

阅读 2.1k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题