0

I'm attempting to replace a library for testing.

The code I want to change:

import foo from 'foo-lib'; // foo-lib is a library dependency in package.json

I want this to import src/mock-foo.js instead.

This is for end-to-end tests, so I can't use something like Jest mocks.

I have a development-only webpack.config. In that I've tried:

  resolve: {
    alias: {
      'foo-lib': path.resolve(__dirname, 'src/mock-foo.js')
    },
    extensions: ['.js'], // need this for some other aliases (not shown)
  },

I've also tried the older technique in the plugins array:

  new webpack.NormalModuleReplacementPlugin(
    /foo-lib/,
    'mock-foo.js'
  ),

as well as several variations on these.

I don't get errors, but the original library loads every time.

Is this even possible? If so, what's the correct syntax?

TrueWill
  • 25,132
  • 10
  • 101
  • 150

1 Answers1

0

I think I've found one solution based on Replacing/aliasing a file using Webpack .

Testing with the is-number library (just for a simple example), this works:

  plugins: [
    new webpack.NormalModuleReplacementPlugin(
      /is-number/,
      require.resolve('./src/mock.js')
    ),
  ],

As one of the commenters on the other post mentioned, it's not clear why the resolve.alias approach didn't work.

TrueWill
  • 25,132
  • 10
  • 101
  • 150