Skip to content

vue-cli 项目为开发/生产环境引用不同的外部 JS 库 #47

@Dream4ever

Description

@Dream4ever

需求描述

前面实现了 vue-cli 项目中引用 CDN 上的 JS/CSS 库,那么另一个问题就随之而来了:开发环境和生产环境,需要引用同一个 JS 库的不同版本,该如何实现?

方案调研

调研过程

之前研究 jantimon/html-webpack-plugin 这个 webpack 插件,看到官方文档中介绍用户可以自定义 index.html 或者页面模板的内容,从而尽量满足用户的个性化需求:

plugins: [
  new HtmlWebpackPlugin({
    title: 'Custom template',
    template: 'index.html'
  })
]
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
  </body>
</html>

既然有这个功能,那么是不是可以编辑 webpack 的配置文件,从而实现在开发/生产环境下引用不同的 JS 库的需求呢?说干就干。

入选方案

应用过程

因为要在开发环境下和生产环境下分别引用不同的 JS 库,那么就需要先了解一下 webpack 是如何为两种环境传入不同的设置的。因为已经用了相当一段时间的 vue-cli 了,所以知道整体的配置流程,先在 config 目录下新建 cdn.js,内容如下:

// config/cdn.js
'use strict';

module.exports = {
  dev: {
+    vue: 'https://cdn.bootcss.com/vue/2.5.16/vue.js',
  },
  build: {
+    vue: 'https://cdn.bootcss.com/vue/2.5.16/vue.min.js',
  }
}

添加了开发环境和生产环境下要用的 vue 的链接之后,再设置这两种环境下的 webpack 编译配置:也就是编辑 build/webpack.dev.conf.jsbuild/webpack.prod.conf.jshtml-webpack-plugin 插件的设置,这样才能在 index.html 中按需引用 JS 库:

// build/webpack.dev.conf.js
const cdn = require('../config/cdn');
...
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
+       vueSrc: config.dev.vue,
      inject: true
    }),
  ]
// build/webpack.prod.conf.js
const cdn = require('../config/cdn');
...
  plugins: [
    new HtmlWebpackPlugin({
      filename: config.build.index,
      template: 'index.html',
+       vueSrc: config.build.vue,
      inject: true,
    }),
  ]

最后再编辑 index.html,就可以在两种环境下分别引入不同版本的 JS 库了:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>pages</title>
+     <script src="<%= htmlWebpackPlugin.options.vueSrc %>"></script>
  </head>
</html>

这样一来,webpack 就会根据当前设置的环境,自动为 index.html 引入对应的 JS 库,爽!

要点总结

之前总是觉得 webpack 非常复杂,现在再看,其实没那么可怕,把需要解决的问题一个个搞定,最后就会发现还是很简单的。

Metadata

Metadata

Assignees

No one assigned

    Labels

    Front-endEverything you see and experience

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions