Ashit Vora
Ashit Vora

Reputation: 2922

How to add static JS file route in Vue-CLI web-server?

I need to bypass a specific Javascript file from web-server that comes by default in vue-cli (Webpack Dev Server) such that I can open the js file directly from the browser.

It is for Firebase Messaging Service Worker and hence it needs to be in the root.

Eg. http://localhost:8080/firebase-messaging-sw.js

Upvotes: 2

Views: 423

Answers (1)

mirjan
mirjan

Reputation: 11

In webpack.dev.conf.js add next code

  1. require fs
  2. add before hook to devServer conf.

example:

const fs = require('fs')
const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    rules:rules
  },
  devtool: config.dev.devtool,
  devServer: {
    clientLogLevel: 'warning',
     before(app){
       app.get('/firebase-messaging-sw.js', function(req, res) {
          let content = fs.readFileSync(path.resolve(__dirname, '../src/firebase-messaging-sw.js'), 'utf-8')
          res.header("Content-Type", "text/javascript");
          res.send(content)
          return res
    });
},

And don`t forget copy the file in prod mode.

new CopyWebpackPlugin([
  {
    from: path.resolve(__dirname, '../src/firebase-messaging-sw.js'),
    to: config.build.assetsRoot + '/firebase-messaging-sw.js'
  }
]),

Upvotes: 1

Related Questions