将Vue组件导出为npm模块

时间:2018-01-30 14:55:44

标签: vuejs2

我有问题让Vue组件导出正常工作。 我可以成功导出组件,当我尝试在不同的项目中导入它时,我收到此错误:

[Vue warn]: Failed to mount component: template or render function not defined.

这是我用于导出的Webpack配置:

const webpack = require('webpack');
const path = require('path');
const utils = require('./utils');

function resolve(dir) {
  return path.join(__dirname, '..', dir)
}

var config = {
  entry: path.resolve(__dirname + '/../src/components/index.js'),
  output: {
    path: path.resolve(__dirname + '/../dist/timer-comp/'),
    filename: 'timer-component.js',
  },
  resolve: {
    extensions: ['.vue', '.js', '.json']
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      }
    ]
  },
  plugins: [
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
    new webpack.optimize.UglifyJsPlugin({
      minimize: true,
      sourceMap: false,
      mangle: true,
      compress: {
        warnings: false
      }
    })
  ]
};

module.exports = config;

这是我用来导出组件的代码:

import TimerComponent from './timer-component';

export {
  TimerComponent,
};

最后是组件代码:

<template>
  <div>
    <div class="time">{{time}}</div>
  </div>
</template>

<script>
  export default {
    name: 'TimerComponent',
    data() {
      return {
        time: ''
      };
    },
    created() {
      setInterval(() => {
        let now = new Date();
        this.time = now.getHours() + " : " + now.getMinutes() + " : " + now.getSeconds();
      }, 1000);
    }
  }
</script>

<style scoped>

</style>

是否有人知道我为何会收到此错误无法安装组件?

顺便说一下,这就是我在不同项目中调用组件的方式:

import TimerComponent from 'timer-comp';

似乎问题是由于某种程度的构建造成的,但我无法弄清楚可能是什么问题。

1 个答案:

答案 0 :(得分:0)

在生产webpack配置文件中添加输出属性:

output: {
  path: path.resolve(__dirname + '/../dist/timer-comp/'),
  filename: 'timer-component.js',
  libraryTarget: 'umd',
  libraryExport: 'default',
  library: 'TimerComponent',
  umdNamedDefine: true
}