Force Babel to transform import into require?

Viewed 1232

After I upgrade from Node 12 to Node 14, Babel stopped transforming import into require. Here's my Babel config:

export default {
  presets: [
    ['@babel/preset-env', {
      useBuiltIns: 'usage',
      corejs: '3',
      modules: false,
      targets: {
        node: 12,
      },
    }],
    '@babel/preset-typescript',
  ],
  plugins: [
    '@babel/plugin-syntax-dynamic-import',
    '@babel/plugin-proposal-class-properties',
    '@babel/plugin-proposal-optional-chaining',
  ],
  sourceType: 'unambiguous',
  overrides: [
    {
      test: ['./web'],
      presets: [
        ['@babel/preset-env', {
          useBuiltIns: 'usage',
          corejs: '3',
        }],
      ],
      plugins: [
        '@babel/plugin-transform-react-jsx',
        ['module-resolver', {
          root: ['./shared', './web'],
          extensions: ['.js', '.jsx', '.ts', '.tsx'],
        }],
      ],
      env: {
        production: {
          plugins: ['transform-react-remove-prop-types'],
        },
      },
    },
    {
      test: ['./server'],
      plugins: [
        ['module-resolver', {
          root: ['./shared', './server'],
          extensions: ['.js', '.jsx', '.ts', '.tsx'],
        }],
      ],
    },
    {
      test: ['./shared'],
      plugins: [
        ['module-resolver', {
          root: ['./shared'],
          extensions: ['.js', '.jsx', '.ts', '.tsx'],
        }],
      ],
    },
  ],
};

How can I get Babel to transform import?

1 Answers

You should set @babel/preset-env's modules option to 'cjs' so that it transforms your module to CommonJS (which uses require). A value of false tells Babel not to perform a module transform.

Babel's docs:

"amd" | "umd" | "systemjs" | "commonjs" | "cjs" | "auto" | false, defaults to "auto".

Enable transformation of ES module syntax to another module type. Note that cjs is just an alias for commonjs.

Setting this to false will preserve ES modules. Use this only if you intend to ship native ES Modules to browsers. If you are using a bundler with Babel, the default modules: "auto" is always preferred.

Related