美文网首页
Vue封装插件并发布到npm上

Vue封装插件并发布到npm上

作者: 舞月奇影 | 来源:发表于2018-10-11 21:20 被阅读0次

    目录

    • Vue封装插件
      • 创建项目
      • 修改配置
      • 测试插件
    • 发布插件到npm
    • 文章参考

    Vue封装插件

    1. 创建项目

    这里采用Vue官方提供的 webpack-simple 脚手架

    vue init webpack-simple 项目名称
    

    项目结构如下图


    项目结构.png

    index.js 文件,用来封装 ws-carousel.vue组件

    //index.js
    import WsCarousel from './ws-carousel.vue'
    
    const carousel={
      install:function (Vue) {
        Vue.component(WsCarousel.name,WsCarousel)
      }
    }
    
    //global 情况下自动安装
    if(typeof window!=undefined&&window.Vue){
      window.Vue.use(carousel)
    }
    
    export default carousel
    

    2. 修改配置

    2.1 配置package.json

    //package.json
    
    {
      "name": "ws-carousel",
      "description": "vue 轮播图组件",
      "version": "1.0.0",
      "author": "Administrator <1535703141@qq.com>",
    // 配置main结点,如果不配置,我们在其他项目中就不能用import XX from '包名'来引用了,
    //只能以包名作为起点来指定相对的路径
      "main":"dist/vue-carousel.js",
      "license": "MIT",
      "private": false,
      "scripts": {
        "dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot",
        "build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
      },
      "dependencies": {
        "vue": "^2.5.11"
      },
      "browserslist": [
        "> 1%",
        "last 2 versions",
        "not ie <= 8"
      ],
      "devDependencies": {
        "babel-core": "^6.26.0",
        "babel-loader": "^7.1.2",
        "babel-preset-env": "^1.6.0",
        "babel-preset-stage-3": "^6.24.1",
        "cross-env": "^5.0.5",
        "css-loader": "^0.28.7",
        "file-loader": "^1.1.4",
        "node-sass": "^4.5.3",
        "sass-loader": "^6.0.6",
        "vue-loader": "^13.0.5",
        "vue-template-compiler": "^2.4.4",
        "webpack": "^3.6.0",
        "webpack-dev-server": "^2.9.1"
      },
      "keywords": ["vue","carousel"]
    }
    

    2.2 配置webpack.config.js,需配置entry和output

    //webpack.config.js
    var path = require('path')
    var webpack = require('webpack')
    
    module.exports = {
    //更改入口和出口文件名
      entry: './src/lib/carousel/index.js',
      output: {
        path: path.resolve(__dirname, './dist'),
        publicPath: '/dist/',
        filename: 'vue-carousel.js',
        library:'VueCarousel',
    // libraryTarget 改为 umd 后,同时可用<script>标签引用组件
        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/dist/vue.esm.js'
        },
        extensions: ['*', '.js', '.vue', '.json']
      },
      devServer: {
        historyApiFallback: true,
        noInfo: true,
        overlay: true
      },
      performance: {
        hints: false
      },
      devtool: '#eval-source-map'
    }
    
    if (process.env.NODE_ENV === 'production') {
      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
        })
      ])
    }
    
    

    2.3 配置 .gitignore文件,要用dist文件夹,所以在.gitignore文件中把dist/去掉
    2.4 配置 index.html

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>npmtest</title>
      </head>
      <body>
        <div id="app"></div>
    <!-- 将 script标签改为webpack.config.js output声明的出口文件-->
        <script src="/dist/vue-carousel.js"></script>
      </body>
    </html>
    
    

    3. 测试插件

    打包插件

    npm run build
    npm pack
    

    npm pack之后,会在当前目录生成一个tgz格式文件
    打开一个新的Vue项目,执行如下

    npm install tgz文件路径/组件名称.tgz
    

    在新项目的入口文件中引入该组件

    import 变量名 from '组件名称'
    
    Vue.use(变量名)
    

    插件封装完毕,接下来就可以使用了


    发布到NPM

    • 在 npm官网 注册一个npm账号
    • 切换到需要发包的项目根目录下,npm login登录npm账号,输入用户名、密码、邮箱
    • 最后一步,执行npm publish

    发布到NPM后,使用插件时,就可以用npm install 组件名称 来安装


    文章参考

    相关文章

      网友评论

          本文标题:Vue封装插件并发布到npm上

          本文链接:https://www.haomeiwen.com/subject/zhliaftx.html