vue-cli2 单个组件打包为js

本文详细介绍了如何在Vue CLI 2环境中,正确配置webpack将单个组件打包成可独立引用的js文件,包括设置入口文件、输出路径、UMD模块化以及解决组件导入和使用的问题。同时讨论了如何在HTML中引入和初始化这些组件,以及开发组件时遇到的常见坑点和解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue-cli2 单个组件打包为js

vue-cli项目的运行流程详见我的博客

vue-cli2和vue-cli3

参考这篇文章
还有这篇文章
vue-cli3有更多的默认配置支持更多场景,支持直接把组件打包成js的脚本,不用配置

vue-cli2

vue-cli2开发小组件建议直接使用vue init webpack-simple xxx创建项目,默认没有导入route。或者把vue init webpack-simple xxx生成的vue.config.js复制一份到vue普通项目中,后新建运行脚本。

vue.config.js

var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: '改成组件的js',
  output: {
    path: path.resolve(__dirname, './lib'),//所有输出文件的目标路径;打包后文件在硬盘中的存储位置。
    publicPath: '/lib/',//index.html 可访问资源
    filename: 'autobg.js',
    library: 'autobg',
    libraryTarget: 'umd',
    umdNamedDefine: true
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ],
      },
      {
        test: /\.scss$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader'
        ],
      },
      {
        test: /\.sass$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader?indentedSyntax'
        ],
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
            // the "scss" and "sass" values for the lang attribute to the right configs here.
            // other preprocessors should work out of the box, no loader config like this necessary.
            'scss': [
              'vue-style-loader',
              'css-loader',
              'sass-loader'
            ],
            'sass': [
              'vue-style-loader',
              'css-loader',
              'sass-loader?indentedSyntax'
            ]
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/lib/vue.esm.js'
    },
    extensions: ['*', '.js', '.vue', '.json']
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true,
    overlay: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: '"production"'
    }
  }),
  new webpack.optimize.UglifyJsPlugin({
    sourceMap: true,
    compress: {
      warnings: false
    }
  }),
  new webpack.LoaderOptionsPlugin({
    minimize: true
  })
])

package.json

"scripts": {
    "dev": "webpack-dev-server --open --hot",
    "build": "webpack --progress --hide-modules"
  }

添加route依赖命令

npm install route --save 

组件的index.js注意事项

在vue-cli项目中使用组件和html引用js使用组件需要

import Vue from 'vue'
import Axios from 'axios'
import xxx from 'xxx'
import newComponent from 'xxx'

init(Vue);//让该项目可在npm run dev 中运行

function init(Vue){
if(Vue){
  Vue.prototype.$axios = Axios
  Vue.use(xxx)
  Vue.component(newComponent.name, newComponent)
}
}


if (typeof window !== 'undefined' && window.Vue) {//在html中引入js使用该组件
init(window.Vue);
}

AutoBGManagement.install = function (vue) {//vue-cli中使用该组件
init(vue);
}

export default newComponent

使用vue-cli2开发组件的坑

  • 因为主攻后端开发,前端没有系统的学习过webpack,想要使用vue-cli2打包组件,达到在html页面引入js的效果时,要是用umd的打包格式,详见:
    Common JS、AMD、CMD和UMD的区别
  • 组件项目下建立packages文件夹来开发组件,在packages文件夹下建立index.js用于扫描子文件夹自动引入所有组件,这样就不用每次开发一个组件就import一个组件了。不知道为什么这里写install方法use所有子组件会导致循环引用,而在mian.js中use所有组件则无问题。
var res = {}
importPages(require.context('../packages/', true, /\.js$/))
function importPages(requireComponent) {
    requireComponent.keys().forEach(key => {
        console.log(key)
        if (key != './index.js') {
            res[(key.split('/'))[1]] = requireComponent(key).default;
        }
    });
}
//在这里use不知到为什么会循环引用,在main.js里面则不会
// function init(curVue) {
//     if (curVue) {
//         for (let key in res) {
//             curVue.use(res[key])
//         }
//     }
// }
// res.install = function (vue) {//vue-cli中使用该组件
//     init(vue);
// }
export default res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值