gremo
gremo

Reputation: 48909

Making Snowpack work with Babel, "require is not defined". Am I missing a require transformation?

I'm approaching Snowpack, previously used Webpack + Babel loader. I'm missing something and I know what: some sort of require polyfill or transformation. I don't know the internals of Webpack that make require work in the browser, but I can't get the same with Snowpack.

In my snowpack.config.json I'm loading the Babel plugin:

{
  "buildOptions": {
    "clean": true,
    "out": "dist"
  },
  "mount": {
    "src": "/"
  },
  "plugins": [
    "@snowpack/plugin-babel"
  ]
}

My .babelrc is using @babel/preset-env:

{
  "presets": [
    ["@babel/preset-env", {
      "corejs": 3,
      "useBuiltIns": "usage"
    }]
  ]
}

A test script is transformed using snowpack build into this:

"use strict";

require("core-js/modules/es.array.concat");

require("core-js/modules/es.array.map");

// Import polyfill
document.addEventListener('DOMContentLoaded', function () {
  [1, 2, 3].concat([4, 5]).map(function (n) {
    return console.log(n);
  });
});

window.addEventListener('load', function () {});

(The problem, of course, is that require is not defined)

Upvotes: 1

Views: 1093

Answers (1)

amankkg
amankkg

Reputation: 5061

Babel still transpiles import statements to require with your config. In order to prevent this try the following configuration:

{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "esmodules": true
      },
      "modules": false
    }]
  ]
}

You can extend it with your additional settings, but this should be a minimal working setup.

As I mentioned in comments, without modules: false it still can transpile to require statements, so you have to override default behavior as per docs

Upvotes: 1

Related Questions