Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

vue.js - Embed script only on production with Vue CLI 3

My main goal is to inject a tag into my index.html only in production (it's a New Relic monitoring code snippet).

My Vue.js is built and served as a static resource, so using {% %} tags to surround the script block with a condition doesn't seem to work in this use case.

So I tried to add the New Relic code snippet on my Vue.js app using html-webpack-plugin, since I found a simple Webpack plugin using on html-webpack-plugin. It's a pretty simple plugin, it just create the node and pushes it in the page body : https://github.com/robrap/html-webpack-new-relic-plugin/blob/master/src/index.js#L25

I register the plugin by setting my vue.config.js this way (I first tried to add the script no matter the environment) :

var HtmlWebpackPlugin = require('html-webpack-plugin');
var HtmlWebpackNewRelicPlugin = require('@yodatech/html-webpack-new-relic-plugin');

module.exports = {
  configureWebpack: {
    plugins: [
      new HtmlWebpackPlugin(),
      new HtmlWebpackNewRelicPlugin({the plugin options})
    ]
  }
}

The plugin actually does its job well (the code snippet is injected), but its execution messes up with Vue CLI default configuration.

Some stylesheets and scripts aren't referenced anymore in the final index.html file, the <div id=app></div> is not there anymore, the app is broken.

I don't know if using HtmlWebpackPlugin is a dead end, but I currently don't know any other way to reach my goal.

Has anyone an idea on how I could make this work ?

Thanks a lot to anyone passing by.

EDIT : The plugin I was trying to use seemed to be flawed, I had to modify it to make it work with Vue CLI. My main problem has been solved by the selected answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

vue.config.js option configureWebpack just merges the options you provide to a webpack config provided by Vue CLI. So by using your code, you are running 2 distinct HtmlWebpackPlugins (one from your config and one default from Vue CLI)

Try this instead:

var HtmlWebpackNewRelicPlugin = require('@yodatech/html-webpack-new-relic-plugin');

module.exports = {
  configureWebpack: {
    plugins: [
      new HtmlWebpackNewRelicPlugin({the plugin options})
    ]
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...