Nuxt/examples/plugins-vendor/README.md

73 lines
2.0 KiB
Markdown
Raw Normal View History

2016-11-18 03:02:43 +00:00
# Using external modules and plugins with nuxt.js
2016-11-08 01:57:55 +00:00
## Configuration: `build.vendor`
2016-11-08 01:57:55 +00:00
> Nuxt.js allows you to add modules inside the `vendor.bundle.js` file generated to reduce the size of the app bundle. It's really useful when using external modules (like `axios` for example)
To add a module/file inside the vendor bundle, add the `build.vendor` key inside `nuxt.config.js`:
2016-11-08 01:57:55 +00:00
```js
const { join } = require('path')
module.exports = {
build: {
vendor: [
'axios', // node module
join(__dirname, './js/my-library.js') // custom file
]
}
2016-11-08 01:57:55 +00:00
}
```
## Configuration: `plugins`
> Nuxt.js allows you to define js plugins to be ran before instantiating the root vue.js application
I want to use [vue-notifications](https://github.com/se-panfilov/vue-notifications) to validate the data in my inputs, I need to setup the plugin before launching the app.
2016-11-08 01:57:55 +00:00
File `plugins/vue-notifications.js`:
2016-11-08 01:57:55 +00:00
```js
import Vue from 'vue'
import VueNotifications from 'vue-notifications'
2016-11-08 01:57:55 +00:00
Vue.use(VueNotifications)
2016-11-08 01:57:55 +00:00
```
Then, I add my file inside the `plugins` key of `nuxt.config.js`:
```js
const { join } = require('path')
module.exports = {
build: {
vendor: ['vue-notifications']
},
2016-11-16 16:55:15 +00:00
plugins: [ '~plugins/vue-notifications') ]
2016-11-08 01:57:55 +00:00
}
```
2016-11-16 16:55:15 +00:00
I use `~plugins` here because nuxt.js create an alias for the `plugins/` folder, it's equivalent to: `join(__dirname, './plugins/vue-notifications.js')`
I added `vue-notifications` in the `vendor` key to make sure that it won't be included in any other build if I call `require('vue-notifications')` in a component.
2016-11-08 01:57:55 +00:00
### Only in browser build
Some plugins might work only in the browser, for this, you can use the `process.BROWSER` variable to check if the plugin will run from the server or from the client.
2016-11-08 01:57:55 +00:00
Example:
```js
import Vue from 'vue'
import VueNotifications from 'vue-notifications'
2016-11-08 01:57:55 +00:00
if (process.BROWSER) {
Vue.use(VueNotifications)
2016-11-08 01:57:55 +00:00
}
```
## Demo
```bash
npm install
npm start
```
Go to [http://localhost:3000](http://localhost:3000) and navigate trough the pages.