使用webpack将所有组件打包起来,并通过script标签直接使用

使用webpack将所有组件打包起来,并通过script标签直接使用

需求:需要将所有的组件打包起来,通过script标签引入html页面,在页面上使用自定义的组件名就能直接使用,就像element-ui

效果如下:

<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<link rel="stylesheet" href="./app.2780147b.css">
	<script src="https://unpkg.com/vue/dist/vue.js"></script>
	<!-- 自己写的组件,直接引用,在html页面中就能使用 -->
	<script src="./myLib.js"></script>
</head>
<body>
	<div id="app">
		<op-check-box></op-check-box>
	</div>

	<script>
	  new Vue({
	    el: '#app'
		})
	</script>
</body>
</html>

一、项目结构图:

二、组件中的index.js代码

import checkBox from './src/checkBox'

checkBox.install = function (Vue) {
  Vue.component(checkBox.name, checkBox)
}

export default checkBox

 三、index.js打包入口文件

import Vue from 'vue'

import Radio from './packages/radio/src/radio.vue'
import CheckBox from './packages/checkBox/src/checkBox.vue'

Vue.config.productionTip = false

const components = [
  Radio,
  CheckBox
]

// 将所有组件注册在Vue上
const install = function (Vue) {
  components.forEach(component => {
    Vue.component(component.name, component)
  })
}

if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue)
}

export default components

四、在package.json中加入

与name同级,myLib.js为你的库名

  "main": "dist/myLib.js",

五、webpack.config.js配置如下

注意:如报错,根据对应的提示配置对应的 loader 就行,如:笔者使用的 scss,你可能使用的是 less。

到这里就已经完成了,当然你也可以将这个包发布到npm上,就可以在项目上直接下载使用了。

const path = require('path')
const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
  mode: 'production',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'myLib.js',
    library: 'myLib',
    libraryTarget: 'umd'
  },

  plugins: [
    new VueLoaderPlugin()
  ],
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.css|.scss$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader'
        ]
      }
    ]
  }
}

猜你喜欢

转载自blog.csdn.net/qq_16687863/article/details/107709734