Dave Stein
Dave Stein

Reputation: 9316

Why can't I resolve nodejs default modules when using preset-env node?

I am writing a plugin for an app that runs Chromium Embedded Framework (CEF) with an older version of Node.

I threw webpack & babel into the app. When I run webpack, it fails on a file that has const fs = require('fs');, or any other default node package. This is happening both for my code and dependencies:

Module not found: Error: Can't resolve 'fs' in '/Users/me/repositories/myrepo/node_modules/chokidar'

My .babelrc is the following:

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

My webpack config is essentially:

module.exports = {
  entry: './src/main.jsx',
  mode: process.env.NODE_ENV,
  devtool: isDev ? 'eval-source-map' : false,
  output: {
    path: PLUGINDIR,
    filename: 'main.js',
    libraryTarget: 'umd'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          plugins: ['transform-react-jsx']
        }
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },

  resolve: {
    extensions: ['.js', '.jsx', '.css']
  }
};

Upvotes: 5

Views: 230

Answers (1)

Dave Stein
Dave Stein

Reputation: 9316

webpack config also needs target: 'node'. Doing it just in .babelrc was not enough.

Upvotes: 2

Related Questions