同有个疑问,cdn区分开发版本和生产版本呀。怎么去动态设置呢??
在 webpack 的HtmlWebpackPlugin中直接定义一个变量,比如 cdn_scripts
const cdn_scripts = ['/static/js/my-3rd-lib-in-static-dir.min.js', 'http://jquery...', 'http://axios...']if(process.env.NODE_ENV === 'production'){ cdn_scripts.push('http://vue.min.js...') }else { cdn_scripts.push('http://vue.js...') }new HtmlWebpackPlugin({ ...其他配置略, cdn_scripts: cdn_scripts })
然后在 index.html </body> 前面添加:
<% for (var i = 0; i < htmlWebpackPlugin.options.cdn_scripts.length; i++) { %> <script src="<%= htmlWebpackPlugin.options.cdn_scripts[i] %>"></script> <% } %>
或者
const is_prod = process.env.NODE_ENV === 'production'const min = is_prod ? '.min' : ''const cdn_scripts = [ '/static/js/my-3rd-lib-in-static-dir.min.js', `//cdn.bootcss.com/jquery/3.4.0/jquery.slim${min}.js`, `//cdn.bootcss.com/vue/2.6.10/vue${min}.js`, `//cdn.bootcss.com/axios/0.19.0-beta.1/axios${min}.js`, ]
更简单的
const cdn_html = ` <script src="//cdn.bootcss.com/jquery/3.4.0/jquery.slim${min}.js"></script> <script src="//cdn.bootcss.com/axios/0.19.0-beta.1/axios${min}.js"></script> <script src="//cdn.bootcss.com/lodash.js/4.17.12-pre/lodash${min}.js"></script> <script src="//cdn.bootcss.com/vuex/3.1.0/vuex${min}.js"></script> <script src="//cdn.bootcss.com/vue/2.6.10/vue${min}.js"></script> <script src="//cdn.bootcss.com/vue-router/3.0.6/vue-router${min}.js"></script> <link rel="stylesheet" link="//cdn.bootcss.com/xxx.css" > `new HtmlWebpackPlugin({ ...其他配置略, cdn_html: cdn_html })
然后 </body> 前面直接添加:
<%= htmlWebpackPlugin.options.cdn_html %>