Vue 如何import服务器上的js配置文件

背景

项目中有一个本地配置文件:

// src/image-position.js
export default {
    label: '首页',
    value: 'home',
    data: [
      {
        label: '轮播',
        value: 'carousel'
      }
    ]
}

如何引用一个本地文件大家都知道:

import ImagePosition from './image-position.js'

现在需要把image-position.js文件丢到服务器上去,得到它的链接:

xxx.com/static/imag…

这个时候你直接引用文件地址自然是行不通的。

import ImagePosition from 'https://xxx.com/static/image-position.js'

// ERROR This dependency was not found

实现

首先对image-position.js做一点小改造,暴露一个全局对象ImagePosition

// 改造后的image-position.js

(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' 
    ? module.exports = factory() 
    : typeof define === 'function' && define.amd 
    ? define(factory) 
    : (global = global || self, global.ImagePosition = factory());
}(this, (function () {
  'use strict';
  
  return {
    label: '首页',
    value: 'home',
    data: [
      {
        label: '轮播',
        value: 'carousel'
      }
    ]
  };
})));

在vue.config.js文件里添加externals。

module.exports = {
  configureWebpack: config => {
    config.externals = {
      'image-position': 'ImagePosition'
   }
  }
}

index.html 区分环境并引入js文件。

// public/index.html


  
    
    
    
    
    <%= htmlWebpackPlugin.options.title %>
  
  
    
<% if (NODE_ENV == 'production') { %> <% } else { %> <% } %>

结束上面的步骤后就可以愉快的引用image-position.js文件了。

import ImagePosition from 'image-position'
console.log(ImagePosition)
// {label: '首页',value: 'home',data: [{label: '轮播', value: 'carousel'}]}

补充vue-cli2.0下如何配置

// build/webpack.base.conf.js
module.exports = {
  externals: {
    // 新增
    'image-position': 'ImagePosition'
  }
}
// index.html


  
    
    
    
    
    <%= htmlWebpackPlugin.options.title %>
  
  
    
<% if (process.env == 'production') { %> <% } else { %> <% } %>

总结

在Vue项目的打包体积优化中,cdn加速是常用的一种手段,上面其实就是cdn加速的实现内容,把第三方库通过script标签引入,大大减少打包的vendor.js文件大小。

当我们想把本地文件放到服务器远程化时,关键在于实现步骤的第一步,其他的内容跟配置cdn加速的过程是一样的。

以上就是Vue 如何import服务器上的js配置文件的详细内容,更多关于Vue import js配置文件的资料请关注脚本之家其它相关文章!

你可能感兴趣的:(Vue 如何import服务器上的js配置文件)