简体   繁体   中英

How copy down mockServiceWorker.js file in React application during Webpack build proces to my build folder

I try to setup Mock Service Worker for my React project. My project doesn't use CRA .

I want to intercept GraphQL request and mock it's response for creating an end 2 end test with Cypress.

How do I copy down mockServiceWorker.js file to my build folder (using Webpack), like the other assets images and fonts and so on?

I used the command npx msw init build --save . Then the mockServiceWorker.js has been created.

But as soon as I run npm start and my client and server gets compiled the file mockServiceWorker.js disappears?

Also I need msw in the pipeline on our acceptance environment, to run the Cypress end 2 end test also in the pipeline.

You don't necessarily need to copy the worker script. In most cases, you're using MSW as a development tool. If you involve webpack to serve your development bundle, you're likely to use webpack-dev-server to serve that bundle. Webpack Dev Server supports the static.directory option (previously contentBase in webpack 4) that points to a local directory in your project that should act as the dev server's public directory. That's where you need to initialize the worker into .

$ npx msw init ./public --save

If you indeed use Webpack Dev Server, then make sure you point it to the correct public directory. One of the ways to do this is in your webpack.config.js :

// webpack.config.js
const path = require('path')

module.exports = {
  devServer: {
    static: {
      directory: path.resolve(__dirname, 'public')
    }
  }
}

Note that if you are already serving static assets, you don't have to add any additional webpack configurations. Simply initialize the worker via npx msw init into the same directory that contains your static assets.

If you're serving your webpack builds by some other means, you can utilize copy-webpack-plugin to explicitly copy the worker script from one location to another. However, I'm pretty sure the dev server suggestion above is what you seek.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM