npm 私服包发开,上传和删除

589 阅读2分钟

一, 使用 vue init webpack-simple my-npm-custom 初始化项目

说明:使用webpack-simple足够了

二, 输入npm install , npm run dev 让项目跑起来

三, 开始写组件

1, 在src目录下新建components文件夹,然后在此文件夹下建立my-custom.vue文件

说明:my-custom.vue 名字也可以是其他,我们写的这个组件就是放在该文件里面

2,在webpack.config.js同级目录下新建 index.js文件, my-npm-custom.vue是把Main.vue文件暴露出去的出口。

修改完之后的文件目录如下,标红的就是新增的内容

image.png

四:修改文件内容和配置

1,my-custom.vue文件里的内容,写你需要实现的功能

<template>
  <div>
    <div>{{msg}}</div>
    <div>{{propData}}</div>
  </div>
</template>

<script>
export default {
  name: 'my-npm-custom',
  data () {
    return {
      msg: '这个是数据'
    }
  },
  props: {
      propData: {
          type: String,
          default: '默认值'
      }
  }
}
</script>

<style lang="scss">
</style>

2.在App.vue里面引入使用

<template>
  <div>
    <myCustom :propData='initData'/>
  </div>
</template>

<script>
import myCustom from './components/my-custom'
export default {
    data(){
      return {
        initData: '我是initData的数据'
      }
    },
    components:{
      myCustom
    }
}
</script>

<style>

</style>

3.新增的index.js文件内容

import myCustom from './src/components/my-custom'
// import _Vue from 'vue'
// 这一步判断window.Vue是否存在,因为直接引用vue.min.js, 
// 它会把Vue绑到Window上,我们直接引用打包好的js才能正常跑起来。
if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.component('my-custom', myCustom)
}
//这样就可以使用Vue.use进行全局安装了。
myCustom.install = function(Vue){
  if (!Vue) {
    window.Vue = Vue = _Vue
  }
  Vue.component(myCustom.name, myCustom)
}

export default myCustom

4.修改package.json文件

image.png

5.修改 webpack.config.js文件

image.png

var path = require('path')
var webpack = require('webpack')
const NODE_ENV = process.env.NODE_ENV

module.exports = {
  // entry: './src/main.js',
  entry: NODE_ENV == 'development' ? './src/main.js' : './index.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'my-npm-custom.js',
    library: 'my-npm-custom', // 指定的就是你使用require时的模块名
    libraryTarget: 'umd', // libraryTarget会生成不同umd的代码,可以只是commonjs标准的
    //也可以是指amd标准的,也可以只是通过script标签引入的
    umdNamedDefine: true // 会对 UMD 的构建过程中的 AMD 模块进行命名。否则就使用匿名的 define
  },

6.修改index.html的js引用路径,因为我们修改了output 的 filename

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>my-npm-custom</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="/dist/my-npm-custom.js"></script>
  </body>
</html>

五: 件就开发完了,打包下看看,npm run build dist下生成了俩文件

说明:网上说会生成两个文件,但是不知道为什么我的这么多

image.png

六: 发布到npm