简体   繁体   English

如何在NPM上创建和发布Vuejs组件

[英]How to create and publish a Vuejs component on NPM

I started working a lot with vue and started to use it in all the projects in the company where I work. 我开始大量使用vue并开始在我工作的公司的所有项目中使用它。 And with that, I ended up creating some components , in general autocomplete , I know that there are many, I have already used some, but none have supplied all my needs. 至此,我最终创建了一些components ,通常是autocomplete ,我知道有很多组件,我已经使用了一些组件,但是没有一个组件可以满足我的所有需求。 However, whenever I go to work on a new project and use the same component, either I recreates it, or I copy and paste it. 但是,每当我在一个新项目上工作并使用相同的组件时,要么重新创建它,要么复制并粘贴它。

So I came to doubt How to create my component, upload to npmjs for whenever I use it, just give a npm install -save ... , and also be able to contribute a bit with the community. 因此,我开始怀疑如何创建我的组件,无论何时使用它都上传到npmjs,只需给出一个npm install -save ... ,还能为社区做出一点贡献。

update 更新

With the release of vue-loader 15.x this answer will no longer work. 随着vue-loader 15.x的发布,此答案将不再起作用。 Please use this instead https://medium.freecodecamp.org/how-to-create-a-vue-js-app-using-single-file-components-without-the-cli-7e73e5b8244f 请改用此网址https://medium.freecodecamp.org/how-to-create-a-vue-js-app-using-single-file-components-without-the-cli-7e73e5b8244f


Here is one way you can create/publish a Vuejs library/component from scratch. 这是从头开始创建/发布Vuejs库/组件的一种方法。

As I am going to write down every step and command, make sure to follow the entire guide and you will be able to create and publish your own Vuejs component on NPM. 在我写下每个步骤和命令时,请确保遵循整个指南,您将能够在NPM上创建和发布自己的Vuejs组件。

After you publish it, like most libraries you can install it using ex: 发布后,就像大多数库一样,您可以使用ex安装它:

npm install --save your-component 

And then import the component inside your app using 然后使用

import something from 'your-component'

To start creating our first component, first create a folder called vuejs-hello-app (or any other name) and inside it, run: 要开始创建我们的第一个组件,请首先创建一个名为vuejs-hello-app (或任何其他名称)的文件夹,然后在其中运行:

npm init

Just hit enter until the interactive question ends and then npm will generate a file named package.json in that folder containing the following code. 只需按Enter键,直到交互式问题结束,然后npm就会在该文件夹中生成一个名为package.json的文件,其中包含以下代码。

(Note: I changed the description and version from 1.0.0 to 0.1.0 here is the result.) (注意:我将描述和版本从1.0.0更改为0.1.0这是结果。)

{
  "name": "vuejs-hello-app",
  "version": "0.1.0",
  "description": "vuejs library demo",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

After this, we'll need to install the dependencies for our library. 之后,我们需要为我们的库安装依赖项。

These dependencies are divided into two types: dependency and devDependency 这些依赖关系分为两种类型: dependencydevDependency

dependency : dependency
is the external library or libraries that our own component runs on. 是运行我们自己的组件的一个或多个外部库。 When someone installs your component, npm will make sure this dependency exists or gets installed first. 当有人安装您的组件时,npm将确保此依赖项存在或首先安装。 Since we are creating a component for vue, we need to make sure vue is required. 由于我们正在为vue创建组件,因此我们需要确保需要vue。 So, install it using: 因此,使用以下命令安装它:

npm install --save vue

devDependency : devDependency
is a bunch of libraries that we need only for development purposes. 是一堆我们只需要用于开发目的的库。 These libraries will help us build and/or transpile. 这些库将帮助我们构建和/或移植。

We install dev dependencies using the method above by adding the the suffix -dev to --save 我们使用上述方法通过将后缀-dev添加到--save来安装dev依赖项

Now, let us install the minimum dev dependencies we need for our component: 现在,让我们安装组件所需的最小开发依赖项:

npm install --save-dev babel-core
npm install --save-dev babel-loader
npm install --save-dev babel-preset-env
npm install --save-dev cross-env
npm install --save-dev css-loader
npm install --save-dev file-loader
npm install --save-dev node-sass
npm install --save-dev sass-loader
npm install --save-dev vue-loader
npm install --save-dev vue-template-compiler
npm install --save-dev webpack
npm install --save-dev webpack-dev-server

At this point the libraries will be installed and the package.json will be updated to look like following. 此时,将安装库,并将package.json更新为如下所示。

{
  "name": "vuejs-hello-app",
  "version": "0.1.0",
  "description": "vuejs library demo",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack -p"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "cross-env": "^5.1.1",
    "css-loader": "^0.28.7",
    "file-loader": "^1.1.5",
    "node-sass": "^4.7.2",
    "sass-loader": "^6.0.6",
    "vue-loader": "^13.5.0",
    "vue-template-compiler": "^2.5.9",
    "webpack": "^3.10.0",
    "webpack-dev-server": "^2.9.7"
  },
  "dependencies": {
    "vue": "^2.5.9"
  }
}

(note: I have added "build": "webpack -p" to build our lib with webpack) (注意:我添加了"build": "webpack -p"以使用webpack来构建我们的库)

Now, since our code needs to be built and transpiled, we need a folder to store the build version. 现在,由于需要构建和编译代码,因此需要一个文件夹来存储构建版本。 Go ahead and create a folder inside our root folder and call it: dist and in the same place a configuration file for webpack and name it webpack.config.js 继续,在我们的根文件夹中创建一个文件夹,并将其命名为: dist并在同一位置为webpack配置文件并将其命名为webpack.config.js

All of the files we have so far created are for configuring and stuff. 到目前为止,我们创建的所有文件都用于配置和填充。 For the actual app that people are going to use, we need to create at least two files inside our src/ directory. 对于人们将要使用的实际应用程序,我们需要在src/目录中至少创建两个文件。

A main.js and VuejsHelloApp.vue put them as: ./src/main.js and ./src/components/VuejsHelloApp.vue main.jsVuejsHelloApp.vue将它们放置为: ./src/main.js ./src/components/VuejsHelloApp.vue / ./src/main.js./src/components/VuejsHelloApp.vue

I have mine structured like this: 我有这样的结构:

dist
node_modules
src
  main.js
  components
    VuejsHelloApp.vue
.babelrc
.eslintignore
.gitignore
.npmignore
.travis.yml
CONTRIBUTING
LICENSE
package.json
README.md
webpack.config.js

I will just go through the files listed and describe what each file does in-case anyone is curious: 我将只浏览列出的文件,并描述每个文件在有人好奇的情况下的作用:

/dist is where a build (transpiled), minified, non-ES6 version of your code will be stores /dist是将代码的构建(编译),最小化,非ES6版本存储的位置

node_modules I think we know this already, let's ignore it node_modules我认为,我们已经知道了这一点,让我们忽略它

src/ this is root dir of your library. src/这是您的库的根目录。

.babelrc is where your babel options are kept, so add this to disable presets on modules .babelrc是保存babel选项的位置,因此添加此选项可禁用模块上的预设

{
  "presets": [
    [
      "env",
      {
        "modules": false
      }
    ]
  ]
}

.eslintignore This is where you tell ESLINT to ignore linting so put this inside: .eslintignore这是您告诉ESLINT忽略棉绒的地方,因此请将其放入其中:

build/*.js 

.gitignore add files you want to ignore (from git) .gitignore添加您要忽略的文件(来自git)

.npmignore same as .gitignore for NPM .npmignore与NPM的.gitignore相同

.travis.yml if you need CI check examples from travis and configure it .travis.yml如果您需要travis的CI检查示例并对其进行配置)

CONTRIBUTING not required 不需要CONTRIBUTING

LICENSE not required 不需要LICENSE

package.json ignore for now package.json现在忽略

README.md not required README.md

webpack.config.js This is the important file that let's you create a build, browser compatible version of your code. webpack.config.js这是重要的文件,可让您创建兼容浏览器的代码版本。

So, according to our app, here is a minimal example of what it should look like: 因此,根据我们的应用程序,这是它看起来像的最小示例:

var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',

  module: {
    rules: [
      // use babel-loader for js files
      { test: /\.js$/, use: 'babel-loader' },
      // use vue-loader for .vue files
      { test: /\.vue$/, use: 'vue-loader' }
    ]
  },
  // default for pretty much every project
  context: __dirname,
  // specify your entry/main file
  output: {
    // specify your output directory...
    path: path.resolve(__dirname, './dist'),
    // and filename
    filename: 'vuejs-hello-app.js'
  }
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  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
    })
  ])
}

Note that the important directives here are entry and output . 请注意,这里的重要指令是entryoutput You can check webpack docs to learn more if you want to fully customize your app. 如果要完全自定义应用程序,可以查看webpack文档以了解更多信息。

But basically, we're telling webpack to get the ./src/main.js (our app) and output it as ./dist/vuejs-hello-app.js 但基本上,我们是在告诉webpack获取./src/main.js (我们的应用)并将其输出为./dist/vuejs-hello-app.js

Now, we are almost finished setting up everything except the actual app. 现在,我们几乎完成了除实际应用程序之外的所有设置。

Go to /src/components/VuejsHelloApp.vue and dump this simple app, which will move a button right or left when you hover on it 转到/src/components/VuejsHelloApp.vue并转储此简单应用程序,当您将鼠标悬停在该应用程序上时,它将向右或向左移动按钮

<template>
  <div>
    <button @mouseover='move($event)'> I'm alive </button>
  </div>
</template>

<script>
export default {
  data () {
   return {}
  },

  methods: {
    move (event) {
        let pos = event.target.style.float; 
      if(pos === 'left'){
        event.target.style.float = 'right'
      }else{
        event.target.style.float = 'left'
      }
    }
  }
}

</script>

<style scoped>

</style>

And not but not least, got to ./src/main.js and export your app like: 同样重要的是,转到./src/main.js并按以下方式导出您的应用程序:

import VuejsHelloApp from './components/VuejsHelloApp.vue'
export default VuejsHelloApp

Now go to your package.json file replace the "main: "index.js", with "main": "src/main.js", 现在转到您的package.json文件,将"main: "index.js",替换为"main": "src/main.js",

After this, simply run these commands to build and publish your app: 之后,只需运行以下命令即可构建和发布您的应用程序:

npm run build
git add .
git commit -m "initial commit"
git push -u origin master
npm login 
npm publish

Importing and using the library. 导入和使用库。

If everything went smoothly, then simply install your app like this: 如果一切顺利,则只需像这样安装您的应用程序:

npm install --save vuejs-hello-app

And use it in vue like this: 并像这样在vue中使用它:

<template>
  <div>
    <VuejsHelloApp> </VuejsHelloApp>
  </div>
</template>

<script>
import VuejsHelloApp from 'vuejs-hello-app'
export default {
  name: 'HelloWorld',
  components: { VuejsHelloApp }
}
</script>

I made this app https://github.com/samayo/vuejs-hello-app while writing the answer, it might help to better understand the code 我在编写答案时制作了这个应用程序https://github.com/samayo/vuejs-hello-app ,这可能有助于更好地理解代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM