最近搭建了一个NPM私服,就尝试着发布一个VUE自定义组件到私服, 流程如下:
(1)新建VUE工程
vue init webpack vuepub
cd vuepub
npm install
npm run dev
(2)看到如下界面,说明工程搭建成功
(3)在components目录下建立test文件夹,在其下建立test.vue,代码如下:
<template>
<div class="app">
<h1>{{ info }}</h1>
</div>
</template>
<script>
export default {
name: 'cwbTest',
props: {
info: {
type: String,
default: 'hello,world'
}
},
data () {
return {}
}
}
</script>
<style scoped>
h1, h2 {
font-weight: normal;
}
</style>
(4)在test文件下建立index.js,内容如下:
import cwbTest from './test.vue';
cwbTest.install = function (Vue) {
Vue.component(cwbTest.name, cwbTest)
}
export default cwbTest
(5)修改package.json,private 改成false,并添加main字段,并填写发布的文件目录
"name": "@cwb/test",
"private": false,
"main":"dist/index.js",
(6)修改webpack.config.js,内容如下:
entry: './src/components/test/index.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'index.js',
libraryExport: 'default',
//libraryTarget:"commonjs2",
libraryTarget: "umd"
},
(7)再项目根目录下执行如下命令,即可发布:
npm run build
npm login
npm publish
(8)安装已经发布的组件:
npm install @cwb/test --save
(9)引用组件:
<template>
<div id="app">
<img src="./assets/logo.png">
<cwbTest info="hello,world"/>
</div>
</template>
<script>
import cwbTest from '@cwb/test'
export default {
name: 'App',
components: {
cwbTest
},
data(){
return{
dd:"test"
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
(10)效果如下: