Merge branch 'dev' into dev

This commit is contained in:
Sébastien Chopin 2018-01-05 08:18:17 +01:00 committed by GitHub
commit 202a84f203
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
356 changed files with 9516 additions and 3856 deletions

39
.circleci/config.yml Executable file
View File

@ -0,0 +1,39 @@
version: 2
jobs:
build:
working_directory: /usr/src/app
docker:
- image: banian/node-headless-chrome
steps:
# Checkout repository
- checkout
# Restore cache
- restore_cache:
key: yarn-{{ checksum "yarn.lock" }}
# Install dependencies
- run:
name: Install Dependencies
command: NODE_ENV=dev yarn
# Keep cache
- save_cache:
key: yarn-{{ checksum "yarn.lock" }}
paths:
- "node_modules"
# Test
- run:
name: Tests
command: yarn test && yarn coverage
# Release next
- run:
name: Publish nuxt-next
command: |
if [ "${CIRCLE_BRANCH}" == "dev" ]; then
echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc
echo "//registry.yarnpkg.com/:_authToken=$NPM_TOKEN" >> ~/.npmrc
./scripts/release-next && npm publish --tag next
fi

4
.eslintignore Normal file
View File

@ -0,0 +1,4 @@
app
node_modules
dist
.nuxt

View File

@ -8,7 +8,7 @@ module.exports = {
browser: true,
node: true
},
extends: 'standard',
extends: ['standard', 'standard-jsx'],
// required to lint *.vue files
plugins: [
'html'
@ -22,7 +22,14 @@ module.exports = {
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
// do not allow console.logs etc...
'no-console': 2
'no-console': 2,
'space-before-function-paren': [
2,
{
anonymous: 'always',
named: 'never'
}
],
},
globals: {}
}

35
.gitignore vendored
View File

@ -1,18 +1,21 @@
# dependencies
# Dependencies
node_modules
examples/**/*/yarn.lock
jspm_packages
package-lock.json
# logs
# Logs
*.log
npm-debug.log*
# other
.nuxt
# Other
.nuxt*
.cache
# Dist folder
dist
# dist example generation
# Dist example generation
examples/**/dist
# Coverage support
@ -25,5 +28,23 @@ coverage
*.iml
.idea
# Macos
.DS_Store
# OSX
*.DS_Store
.AppleDouble
.LSOverride
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

View File

@ -1,10 +1,13 @@
language: node_js
node_js:
- "8"
- "6"
- "9"
cache:
yarn: true
directories:
- node_modules
install:
- yarn install
- yarn run build
script:
- yarn run test
after_success:

46
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at team@nuxtjs.org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

10
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,10 @@
# Contributing to Nuxt.js
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device.
2. Install the dependencies: `npm install`.
3. Run `npm link` to link the local repo to NPM.
4. Run `npm run build` to build or `npm run watch` to build and watch for code changes.
5. Then npm link this repo inside any example app with `npm link nuxt`.
6. Then you can run your example app with the local version of Nuxt.js (You may need to re-run the example app as you change server side code in the Nuxt.js repository).
Make sure to add tests into `test/` directory and try them with `npm test` before making a pull request.

View File

@ -2,7 +2,7 @@
<p align="center">
<a href="https://travis-ci.org/nuxt/nuxt.js"><img src="https://img.shields.io/travis/nuxt/nuxt.js/master.svg" alt="Build Status"></a>
<a href="https://ci.appveyor.com/project/Atinux/nuxt-js"><img src="https://ci.appveyor.com/api/projects/status/gwab06obc6srx9g4?svg=true" alt="Windows Build Status"></a>
 <a href="https://codecov.io/gh/nuxt/nuxt.js"><img src="https://img.shields.io/codecov/c/github/nuxt/nuxt.js/master.svg" alt="Coverage Status"></a>
 <a href="https://codecov.io/gh/nuxt/nuxt.js"><img src="https://img.shields.io/codecov/c/github/nuxt/nuxt.js/dev.svg" alt="Coverage Status"></a>
<a href="https://www.npmjs.com/package/nuxt"><img src="https://img.shields.io/npm/dm/nuxt.svg" alt="Downloads"></a>
<a href="https://www.npmjs.com/package/nuxt"><img src="https://img.shields.io/npm/v/nuxt.svg" alt="Version"></a>
<a href="https://www.npmjs.com/package/nuxt"><img src="https://img.shields.io/npm/l/nuxt.svg" alt="License"></a>
@ -164,7 +164,7 @@ You can start by using one of our starter templates:
- [koa](https://github.com/nuxt-community/koa-template): Nuxt.js + Koa
- [adonuxt](https://github.com/nuxt-community/adonuxt-template): Nuxt.js + AdonisJS
- [micro](https://github.com/nuxt-community/micro-template): Nuxt.js + Micro
- [nuxtent](https://github.com/nuxt-community/nuxtent-template): Nuxt.js + Nuxtent module for content heavy sites
- [nuxtent](https://github.com/nuxt-community/nuxtent-template): Nuxt.js + Nuxtent module for content heavy sites
## Using nuxt.js programmatically
@ -251,4 +251,7 @@ Note: we recommend putting `.nuxt` in `.npmignore` or `.gitignore`.
## Roadmap
https://github.com/nuxt/nuxt.js/projects/1
https://trello.com/b/lgy93IOl/nuxtjs-10
## Contributing
Please see our [CONTRIBUTING.md](./CONTRIBUTING.md)

View File

@ -1,8 +1,12 @@
# Test against the latest version of this Node.js version
environment:
matrix:
- nodejs_version: "6"
- nodejs_version: "8"
- nodejs_version: "9"
cache:
- "%LOCALAPPDATA%\\Yarn"
- node_modules
# Install scripts. (runs after repo cloning)
install:

29
benchmarks/README.md Normal file
View File

@ -0,0 +1,29 @@
# Nuxt.js server-side benchmarks
> Taken from [Next.js benchmarks](https://github.com/zeit/next.js/tree/master/bench), if you like React, we recommend you to try [Next.js](https://github.com/zeit/next.js).
## Installation
Follow the steps in [CONTRIBUTING.md](../CONTRIBUTING.md).
Both benchmarks use `ab`. So make sure you have it installed.
## Usage
Before running the test:
```
npm run start
```
Then run one of these tests:
- Stateless application which renders `<h1>My component!</h1>`. Runs 3000 http requests.
```
npm run bench:stateless
```
- Stateless application which renders `<li>This is row {i}</li>` 10.000 times. Runs 500 http requests.
```
npm run bench:stateless-big
```

9
benchmarks/package.json Normal file
View File

@ -0,0 +1,9 @@
{
"name": "nuxt-benchmarks",
"scripts": {
"build": "nuxt build",
"start": "npm run build && nuxt start",
"bench:stateless": "ab -c1 -n3000 http://127.0.0.1:3000/stateless",
"bench:stateless-big": "ab -c1 -n500 http://127.0.0.1:3000/stateless-big"
}
}

View File

@ -0,0 +1,5 @@
<template>
<ul>
<li v-for="n in 10000" :key="n">This is row {{ n + 1 }}</li>
</ul>
</template>

View File

@ -0,0 +1,3 @@
<template>
<h1>My component!</h1>
</template>

View File

@ -1,4 +1,5 @@
#!/usr/bin/env node
/* eslint-disable no-console */
// Show logs
process.env.DEBUG = process.env.DEBUG || 'nuxt:*'
@ -75,16 +76,47 @@ if (options.mode !== 'spa') {
builder.build()
.then(() => debug('Building done'))
.catch((err) => {
console.error(err) // eslint-disable-line no-console
console.error(err)
process.exit(1)
})
} else {
const s = Date.now()
nuxt.hook('generate:distRemoved', function () {
debug('Destination folder cleaned')
})
nuxt.hook('generate:distCopied', function () {
debug('Static & build files copied')
})
nuxt.hook('generate:page', function (page) {
debug('Generate file: ' + page.path)
})
nuxt.hook('generate:done', function (generator, errors) {
const duration = Math.round((Date.now() - s) / 100) / 10
debug(`HTML Files generated in ${duration}s`)
if (errors.length) {
const report = errors.map(({ type, route, error }) => {
/* istanbul ignore if */
if (type === 'unhandled') {
return `Route: '${route}'\n${error.stack}`
} else {
return `Route: '${route}' thrown an error: \n` + JSON.stringify(error)
}
})
console.error('==== Error report ==== \n' + report.join('\n\n')) // eslint-disable-line no-console
}
})
// Disable minify to get exact results of nuxt start
nuxt.options.generate.minify = false
// Generate on spa mode
new Generator(nuxt, builder).generate({ build: true }).then(() => {
if (!nuxt.options.dev) {
// eslint-disable-next-line no-console
console.log(`✓ You can now directly upload ${nuxt.options.generate.dir}/ or start server using "nuxt start"`)
}
})

View File

@ -1,4 +1,5 @@
#!/usr/bin/env node
/* eslint-disable no-console */
// Show logs
process.env.DEBUG = process.env.DEBUG || 'nuxt:*'
@ -10,7 +11,9 @@ const fs = require('fs')
const parseArgs = require('minimist')
const { Nuxt, Builder } = require('../')
const chokidar = require('chokidar')
const resolve = require('path').resolve
const path = require('path')
const resolve = path.resolve
const pkg = require(path.join('..', 'package.json'))
const argv = parseArgs(process.argv.slice(2), {
alias: {
@ -19,15 +22,21 @@ const argv = parseArgs(process.argv.slice(2), {
p: 'port',
c: 'config-file',
s: 'spa',
u: 'universal'
u: 'universal',
v: 'version'
},
boolean: ['h', 's', 'u'],
boolean: ['h', 's', 'u', 'v'],
string: ['H', 'c'],
default: {
c: 'nuxt.config.js'
}
})
if (argv.version) {
console.log(pkg.version)
process.exit(0)
}
if (argv.hostname === '') {
console.error(`> Provided hostname argument has no value`)
process.exit(1)
@ -60,42 +69,70 @@ _.defaultsDeep(nuxtConfig, { watchers: { chokidar: { ignoreInitial: true } } })
// Start dev
let dev = startDev()
let needToRestart = false
// Start watching for nuxt.config.js changes
chokidar
.watch(nuxtConfigFile, nuxtConfig.watchers.chokidar)
.on('all', _.debounce(() => {
.on('all', () => {
debug('[nuxt.config.js] changed')
debug('Rebuilding the app...')
dev = dev.then(startDev)
}), 2500)
needToRestart = true
function startDev (oldNuxt) {
dev = dev.then((instance) => {
if (needToRestart === false) return instance
needToRestart = false
debug('Rebuilding the app...')
return startDev(instance)
})
})
function startDev(oldInstance) {
// Get latest environment variables
const port = argv.port || process.env.PORT || process.env.npm_package_config_nuxt_port
const host = argv.hostname || process.env.HOST || process.env.npm_package_config_nuxt_host
// Error handler
const onError = (err, instance) => {
debug('Error while reloading [nuxt.config.js]', err)
return Promise.resolve(instance) // Wait for next reload
}
// Load options
let options = {}
try {
options = loadNuxtConfig()
} catch (err) {
console.error(err)
return // Wait for next reload
return onError(err, oldInstance)
}
// Create nuxt and builder instance
const nuxt = new Nuxt(options)
const builder = new Builder(nuxt)
let nuxt
let builder
let instance
try {
nuxt = new Nuxt(options)
builder = new Builder(nuxt)
instance = { nuxt: nuxt, builder: builder }
} catch (err) {
return onError(err, instance || oldInstance)
}
return Promise.resolve()
.then(() => builder.build()) // 1- Start build
.then(() => oldNuxt ? oldNuxt.close() : Promise.resolve()) // 2- Close old nuxt after successful build
.then(() => nuxt.listen(port, host)) // 3- Start listening
.then(() => nuxt) // 4- Pass new nuxt to watch chain
.then(() => oldInstance && oldInstance.builder ? oldInstance.builder.unwatch() : Promise.resolve())
// Start build
.then(() => builder.build())
// Close old nuxt after successful build
.then(() => oldInstance && oldInstance.nuxt ? oldInstance.nuxt.close() : Promise.resolve())
// Start listening
.then(() => nuxt.listen(port, host))
// Pass new nuxt to watch chain
.then(() => instance)
// Handle errors
.catch((err) => onError(err, instance))
}
function loadNuxtConfig () {
function loadNuxtConfig() {
let options = {}
if (fs.existsSync(nuxtConfigFile)) {

View File

@ -1,4 +1,5 @@
#!/usr/bin/env node
/* eslint-disable no-console */
// Show logs
process.env.DEBUG = process.env.DEBUG || 'nuxt:*'
@ -17,10 +18,11 @@ const argv = parseArgs(process.argv.slice(2), {
s: 'spa',
u: 'universal'
},
boolean: ['h', 's', 'u'],
boolean: ['h', 's', 'u', 'build'],
string: ['c'],
default: {
c: 'nuxt.config.js'
c: 'nuxt.config.js',
build: true
}
})
@ -31,11 +33,11 @@ if (argv.help) {
Usage
$ nuxt generate <dir>
Options
--spa Launch in SPA mode
--spa Launch in SPA mode
--universal Launch in Universal mode (default)
--config-file, -c Path to Nuxt.js config file (default: nuxt.config.js)
--help, -h Displays this message
--no-build Just run generate for faster builds when just dynamic routes changed. Nuxt build is needed before this command.
`)
process.exit(0)
}
@ -62,12 +64,50 @@ debug('Generating...')
const nuxt = new Nuxt(options)
const builder = new Builder(nuxt)
const generator = new Generator(nuxt, builder)
generator.generate()
const generateOptions = {
init: true,
build: argv['build']
}
const s = Date.now()
nuxt.hook('generate:distRemoved', function () {
debug('Destination folder cleaned')
})
nuxt.hook('generate:distCopied', function () {
debug('Static & build files copied')
})
nuxt.hook('generate:page', function (page) {
debug('Generate file: ' + page.path)
})
nuxt.hook('generate:done', function (generator, errors) {
const duration = Math.round((Date.now() - s) / 100) / 10
debug(`HTML Files generated in ${duration}s`)
if (errors.length) {
const report = errors.map(({ type, route, error }) => {
/* istanbul ignore if */
if (type === 'unhandled') {
return `Route: '${route}'\n${error.stack}`
} else {
return `Route: '${route}' thrown an error: \n` + JSON.stringify(error)
}
})
console.error('==== Error report ==== \n' + report.join('\n\n')) // eslint-disable-line no-console
}
})
generator.generate(generateOptions)
.then(() => {
debug('Generate done')
process.exit(0)
})
.catch((err) => {
console.error(err) // eslint-disable-line no-console
console.error(err)
process.exit(1)
})

View File

@ -1,9 +1,10 @@
#!/usr/bin/env node
/* eslint-disable no-console */
const fs = require('fs')
const parseArgs = require('minimist')
const { Nuxt } = require('../')
const { join, resolve } = require('path')
const { resolve } = require('path')
const argv = parseArgs(process.argv.slice(2), {
alias: {
@ -71,7 +72,7 @@ const nuxt = new Nuxt(options)
// Check if project is built for production
const distDir = resolve(nuxt.options.rootDir, nuxt.options.buildDir || '.nuxt', 'dist')
if (!fs.existsSync(distDir)) {
console.error('> No build files found, please run `nuxt build` before launching `nuxt start`') // eslint-disable-line no-console
console.error('> No build files found, please run `nuxt build` before launching `nuxt start`')
process.exit(1)
}
@ -79,7 +80,6 @@ if (!fs.existsSync(distDir)) {
if (nuxt.options.render.ssr === true) {
const ssrBundlePath = resolve(distDir, 'server-bundle.json')
if (!fs.existsSync(ssrBundlePath)) {
// eslint-disable-next-line no-console
console.error('> No SSR build! Please start with `nuxt start --spa` or build using `nuxt build --universal`')
process.exit(1)
}

View File

@ -1,116 +0,0 @@
// Some parts brought from https://github.com/vuejs/vue/blob/dev/build/config.js
const { resolve } = require('path')
const rollupBabel = require('rollup-plugin-babel')
const rollupAlias = require('rollup-plugin-alias')
const rollupCommonJS = require('rollup-plugin-commonjs')
const rollupReplace = require('rollup-plugin-replace')
const rollupNodeResolve = require('rollup-plugin-node-resolve')
const packageJson = require('../package.json')
const dependencies = Object.keys(packageJson.dependencies)
const version = packageJson.version || process.env.VERSION
// -----------------------------
// Banner
// -----------------------------
const banner =
'/*!\n' +
' * Nuxt.js v' + version + '\n' +
' * Released under the MIT License.\n' +
' */'
// -----------------------------
// Aliases
// -----------------------------
const rootDir = resolve(__dirname, '..')
const libDir = resolve(rootDir, 'lib')
const distDir = resolve(rootDir, 'dist')
const aliases = {
core: resolve(libDir, 'core/index.js'),
builder: resolve(libDir, 'builder/index.js'),
common: resolve(libDir, 'common/index.js'),
utils: resolve(libDir, 'common/utils.js'),
app: resolve(libDir, 'app')
}
// -----------------------------
// Builds
// -----------------------------
const builds = {
nuxt: {
entry: resolve(libDir, 'index.js'),
file: resolve(distDir, 'nuxt.js')
},
core: {
entry: resolve(libDir, 'core/index.js'),
file: resolve(distDir, 'core.js')
}
}
// -----------------------------
// Default config
// -----------------------------
function genConfig (opts) {
const config = {
input: opts.entry,
output: {
file: opts.file,
format: 'cjs',
sourcemap: true
},
external: ['fs', 'path', 'http', 'module', 'vue-server-renderer/server-plugin', 'vue-server-renderer/client-plugin']
.concat(dependencies, opts.external),
banner: opts.banner || banner,
name: opts.modulename || 'Nuxt',
plugins: [
rollupAlias(Object.assign({
resolve: ['.js', '.json', '.jsx', '.ts']
}, aliases, opts.alias)),
rollupNodeResolve({ preferBuiltins: true }),
rollupCommonJS(),
rollupBabel(Object.assign({
exclude: 'node_modules/**',
plugins: [
['transform-runtime', { 'helpers': false, 'polyfill': false }],
'transform-async-to-generator',
'array-includes',
'external-helpers'
],
presets: [
['env', {
targets: {
node: '6.11.0'
},
modules: false
}]
],
'env': {
'test': {
'plugins': [ 'istanbul' ]
}
}
}, opts.babel)),
rollupReplace({ __VERSION__: version })
].concat(opts.plugins || [])
}
if (opts.env) {
config.plugins.push(rollupReplace({
'process.env.NODE_ENV': JSON.stringify(opts.env)
}))
}
return config
}
if (process.env.TARGET) {
module.exports = genConfig(builds[process.env.TARGET])
} else {
exports.getBuild = name => genConfig(builds[name])
exports.getAllBuilds = () => Object.keys(builds).map(name => genConfig(builds[name]))
}

View File

@ -12,7 +12,7 @@ const getPost = (slug) => ({
})
export default {
beforeCreate () {
beforeCreate() {
this.component = () => getPost(this.$route.params.slug)
}
}

View File

@ -12,7 +12,7 @@ module.exports = {
},
generate: {
routes: [
'/posts/1',
'/posts/1'
]
}
}

View File

@ -11,12 +11,12 @@
import axios from 'axios'
export default {
async asyncData ({ params }) {
async asyncData({ params }) {
// We can use async/await ES6 feature
let { data } = await axios.get(`https://jsonplaceholder.typicode.com/posts/${params.id}`)
return { post: data }
},
head () {
head() {
return {
title: this.post.title
}

View File

@ -3,7 +3,7 @@
<div class="container">
<h1>Blog</h1>
<ul>
<li v-for="post in posts">
<li v-for="(post, index) in posts" :key="index">
<nuxt-link :to="{ name: 'posts-id', params: { id: post.id } }">{{ post.title }}</nuxt-link>
</li>
</ul>
@ -15,12 +15,12 @@
import axios from 'axios'
export default {
asyncData ({ req, params }) {
asyncData({ req, params }) {
// We can return a Promise instead of calling the callback
return axios.get('https://jsonplaceholder.typicode.com/posts')
.then((res) => {
return { posts: res.data.slice(0, 5) }
})
.then((res) => {
return { posts: res.data.slice(0, 5) }
})
},
head: {
title: 'List of posts'

View File

@ -33,4 +33,4 @@ router.post('/logout', (req, res) => {
module.exports = {
path: '/api',
handler: router
}
}

View File

@ -20,7 +20,7 @@
<script>
export default {
data () {
data() {
return {
formError: null,
formUsername: '',
@ -28,7 +28,7 @@ export default {
}
},
methods: {
async login () {
async login() {
try {
await this.$store.dispatch('login', {
username: this.formUsername,
@ -37,11 +37,11 @@ export default {
this.formUsername = ''
this.formPassword = ''
this.formError = null
} catch(e) {
} catch (e) {
this.formError = e.message
}
},
async logout () {
async logout() {
try {
await this.$store.dispatch('logout')
} catch (e) {

View File

@ -12,12 +12,12 @@ export const mutations = {
export const actions = {
// nuxtServerInit is called by Nuxt.js before server-rendering every page
nuxtServerInit ({ commit }, { req }) {
nuxtServerInit({ commit }, { req }) {
if (req.session && req.session.authUser) {
commit('SET_USER', req.session.authUser)
}
},
async login ({ commit }, { username, password }) {
async login({ commit }, { username, password }) {
try {
const { data } = await axios.post('/api/login', { username, password })
commit('SET_USER', data)
@ -29,7 +29,7 @@ export const actions = {
}
},
async logout ({ commit }) {
async logout({ commit }) {
await axios.post('/api/logout')
commit('SET_USER', null)
}

32
examples/axios/README.md Normal file
View File

@ -0,0 +1,32 @@
# Axios Proxy Example
## Install
```bash
$ yarn add @nuxtjs/axios @nuxtjs/proxy
```
## Nuxt.config.js
```json
{
modules: [
'@nuxtjs/axios',
'@nuxtjs/proxy'
],
proxy: [
['/api/dog', { target: 'https://dog.ceo/', pathRewrite: { '^/api/dog': '/api/breeds/image/random' } }]
]
}
```
### Use Axios
```js
async asyncData({ app }) {
const ip = await app.$axios.$get('http://icanhazip.com')
return { ip }
}
```
More detail, please refer [axios-module](https://github.com/nuxt-community/axios-module).

View File

@ -0,0 +1,9 @@
module.exports = {
modules: [
'@nuxtjs/axios',
'@nuxtjs/proxy'
],
proxy: [
['/api/dog', { target: 'https://dog.ceo/', pathRewrite: { '^/api/dog': '/api/breeds/image/random' } }]
]
}

View File

@ -0,0 +1,14 @@
{
"name": "nuxt-proxy",
"version": "1.0.0",
"dependencies": {
"@nuxtjs/axios": "^4.4.0",
"@nuxtjs/proxy": "^1.1.2",
"nuxt": "latest"
},
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start"
}
}

View File

@ -0,0 +1,17 @@
<template>
<div>
<h1>Dog</h1>
<img :src="dog" />
</div>
</template>
<script>
export default {
async asyncData({ app }) {
const { data: { message: dog } } = await app.$axios.get('/dog')
return { dog }
}
}
</script>

View File

@ -9,11 +9,11 @@
<script>
export default {
name: 'date',
serverCacheKey () {
serverCacheKey() {
// Will change every 10 secondes
return Math.floor(Date.now() / 10000)
},
data () {
data() {
return { date: Date.now() }
}
}

View File

@ -7,8 +7,8 @@ module.exports = {
app: 'app.[chunkhash].js' // default: nuxt.bundle.[chunkhash].js
},
vendor: ['lodash'],
extend (config, { dev }) {
if (dev) {
extend(config, { isDev }) {
if (isDev) {
config.devtool = 'eval-source-map'
}
const urlLoader = config.module.rules.find((loader) => loader.loader === 'url-loader')

View File

@ -8,7 +8,7 @@
<script>
export default {
layout: 'dark',
asyncData ({ req }) {
asyncData({ req }) {
return {
name: req ? 'server' : 'client'
}

View File

@ -10,10 +10,10 @@ export default {
loading: false
}),
methods: {
start () {
start() {
this.loading = true
},
finish () {
finish() {
this.loading = false
}
}

View File

@ -7,7 +7,7 @@
<script>
export default {
asyncData () {
asyncData() {
return new Promise((resolve) => {
setTimeout(function () {
resolve({})

View File

@ -7,7 +7,7 @@
<script>
export default {
asyncData () {
asyncData() {
return new Promise((resolve) => {
setTimeout(function () {
resolve({ name: 'world' })

View File

@ -2,7 +2,7 @@
<div class="container">
<h2>Users</h2>
<ul class="users">
<li v-for="user in users">
<li v-for="user in users" :key="user.id">
<nuxt-link :to="'/users/'+user.id">{{ user.name }}</nuxt-link>
</li>
</ul>
@ -13,7 +13,7 @@
import axios from 'axios'
export default {
async asyncData () {
async asyncData() {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/users')
return { users: data }
}

View File

@ -11,10 +11,10 @@
import axios from 'axios'
export default {
validate ({ params }) {
validate({ params }) {
return !isNaN(+params.id)
},
async asyncData ({ params, error }) {
async asyncData({ params, error }) {
try {
const { data } = await axios.get(`https://jsonplaceholder.typicode.com/users/${+params.id}`)
return data

View File

@ -2,7 +2,7 @@
"name": "nuxt-custom-server",
"dependencies": {
"express": "^4.15.3",
"nuxt": "^1.0.0-rc3"
"nuxt": "latest"
},
"scripts": {
"dev": "node server.js",

View File

@ -21,4 +21,3 @@ app.use(nuxt.render)
// Start express server
app.listen(port, host)
console.log('Server listening on ' + host + ':' + port)

View File

@ -5,7 +5,7 @@ export default async () => {
return VueChart.Bar.extend({
props: ['data'],
mounted () {
mounted() {
this.renderChart(this.data)
}
})

View File

@ -13,12 +13,12 @@ export default {
data: () => ({
loaded: false
}),
beforeMount () {
beforeMount() {
// Preload image
const img = new Image()
img.onload = () => {
this.loaded = true
};
}
img.src = this.data
}
}

View File

@ -6,22 +6,22 @@ export const messages = [
component: 'vChart',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
datasets:[
{
label: 'Activity',
backgroundColor: '#41b883',
data: [40, 20, 12, 39, 10, 40, 39, 50, 40, 20, 12, 11]
}
datasets: [
{
label: 'Activity',
backgroundColor: '#41b883',
data: [40, 20, 12, 39, 10, 40, 39, 50, 40, 20, 12, 11]
}
]
}
},
{ component: 'vText', data: 'End of demo 🎉' },
{ component: 'vText', data: 'End of demo 🎉' }
]
async function streamMessages (fn, i = 0) {
async function streamMessages(fn, i = 0) {
if (i >= messages.length) return
await fn(messages[i])
setTimeout(() => streamMessages(fn, i + 1), 1500)
}
export default streamMessages
export default streamMessages

View File

@ -6,4 +6,4 @@ module.exports = {
{ name: 'viewport', content: 'width=device-width, initial-scale=1' }
]
}
}
}

View File

@ -2,7 +2,7 @@
"name": "dynamic-components-nuxt",
"dependencies": {
"chart.js": "^2.7.0",
"nuxt": "^1.0.0-rc11",
"nuxt": "latest",
"vue-chartjs": "^2.8.7"
},
"scripts": {

View File

@ -16,14 +16,14 @@ const components = {
vText: () => import('@/components/text.vue' /* webpackChunkName: "components/text" */),
vImage: () => import('@/components/image.vue' /* webpackChunkName: "components/image" */),
vCode: () => import('@/components/code.vue' /* webpackChunkName: "components/code" */),
vChart: () => import('@/components/chart.js' /* webpackChunkName: "components/chart" */).then((m) => m.default()),
vChart: () => import('@/components/chart.js' /* webpackChunkName: "components/chart" */).then((m) => m.default())
}
export default {
data: () => ({
messages: []
}),
mounted () {
mounted() {
// Listen for incoming messages
streamMessages(async (message) => {
// Wait for the component to load before displaying it

View File

@ -8,7 +8,7 @@
<script>
export default {
layout: ({ isMobile }) => isMobile ? 'mobile' : 'default',
asyncData ({ req }) {
asyncData({ req }) {
return {
name: req ? 'server' : 'client'
}

View File

@ -7,6 +7,6 @@
<script>
export default {
layout: ({ isMobile }) => isMobile ? 'mobile' : 'default',
layout: ({ isMobile }) => isMobile ? 'mobile' : 'default'
}
</script>

View File

@ -1,3 +0,0 @@
# Updating headers with Nuxt.js
https://nuxtjs.org/examples/seo-html-head

View File

@ -1,15 +0,0 @@
<script>
export default {
asyncData ({ req }) {
return {
name: req ? 'server' : 'client'
}
},
render (h) {
return <div>
<p>Hi from {this.name}</p>
<nuxt-link to="/">Home page</nuxt-link>
</div>
}
}
</script>

View File

@ -1,8 +0,0 @@
export default {
render (h) {
return <div>
<h1>Welcome !</h1>
<nuxt-link to="/about">About page</nuxt-link>
</div>
}
}

View File

@ -7,9 +7,9 @@
<script>
export default {
asyncData ({ isStatic, isServer }) {
asyncData() {
return {
name: isStatic ? 'static' : (isServer ? 'server' : 'client')
name: process.static ? 'static' : (process.server ? 'server' : 'client')
}
}
}

View File

@ -4,10 +4,10 @@
<div class="container">
<h1 class="Header__Title">Nuxt i18n</h1>
<nav class="Header__Menu">
<nuxt-link class="Header__Link" :to="path('/')" exact>
<nuxt-link class="Header__Link" :to="$i18n.path('')" exact>
{{ $t('links.home') }}
</nuxt-link>
<nuxt-link class="Header__Link" :to="path('/about')" exact>
<nuxt-link class="Header__Link" :to="$i18n.path('about')" exact>
{{ $t('links.about') }}
</nuxt-link>
<nuxt-link class="Header__Link" v-if="$i18n.locale === 'en'" :to="`/fr` + $route.fullPath" active-class="none" exact>
@ -24,13 +24,7 @@
</template>
<script>
export default {
methods: {
path (url) {
return (this.$i18n.locale === 'en' ? url : '/' + this.$i18n.locale + url)
}
}
}
export default {}
</script>
<style>

View File

@ -6,7 +6,7 @@ module.exports = {
router: {
middleware: 'i18n'
},
plugins: ['~/plugins/i18n.js',],
plugins: ['~/plugins/i18n.js'],
generate: {
routes: ['/', '/about', '/fr', '/fr/about']
}

View File

@ -1,8 +1,8 @@
{
"name": "nuxt-i18n",
"dependencies": {
"nuxt": "^1.0.0-rc9",
"vue-i18n": "^7.0.5"
"nuxt": "latest",
"vue-i18n": "^7.3.2"
},
"scripts": {
"dev": "nuxt",

View File

@ -9,7 +9,7 @@
<script>
export default {
head () {
head() {
return { title: this.$t('about.title') }
}
}

View File

@ -9,7 +9,7 @@
<script>
export default {
head () {
head() {
return { title: this.$t('home.title') }
}
}

View File

@ -3,7 +3,7 @@ import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
export default ({ app, isClient, store }) => {
export default ({ app, store }) => {
// Set i18n instance on app
// This way we can use it in middleware and pages asyncData/fetch
app.i18n = new VueI18n({
@ -14,4 +14,12 @@ export default ({ app, isClient, store }) => {
'fr': require('~/locales/fr.json')
}
})
app.i18n.path = (link) => {
if (app.i18n.locale === app.i18n.fallbackLocale) {
return `/${link}`
}
return `/${app.i18n.locale}/${link}`
}
}

View File

@ -4,7 +4,7 @@ export const state = () => ({
})
export const mutations = {
SET_LANG (state, locale) {
SET_LANG(state, locale) {
if (state.locales.indexOf(locale) !== -1) {
state.locale = locale
}

5
examples/jsx/README.md Normal file
View File

@ -0,0 +1,5 @@
# Render Functions & JSX Example
## Documentation
Vue: https://vuejs.org/v2/guide/render-function.html

View File

@ -0,0 +1,17 @@
<template>
<p v-html="data"></p>
</template>
<script>
export default {
props: {
data: String
}
}
</script>
<style scoped>
p {
padding: 5px 20px;
}
</style>

View File

@ -1,5 +1,5 @@
{
"name": "hello-nuxt-jsx",
"name": "nuxt-jsx",
"dependencies": {
"nuxt": "latest"
},

View File

@ -0,0 +1,21 @@
import Test from '~/components/test.vue'
export default {
head: {
title: 'About Page',
meta: [
{ hid: 'description', name: 'description', content: 'About page description' }
]
},
components: {
Test
},
render() {
return <div class='container'>
<h1>About page</h1>
<test data='I am test component' />
<p><nuxt-link to='/'>Home page</nuxt-link></p>
</div>
}
}

20
examples/jsx/pages/index.js Executable file
View File

@ -0,0 +1,20 @@
export default {
head: {
title: 'Home page 🚀',
meta: [
{ hid: 'description', name: 'description', content: 'Home page description' }
],
script: [
{ src: '/head.js' },
// Supported since 1.0
{ src: '/body.js', body: true },
{ src: '/defer.js', defer: '' }
]
},
render() {
return <div class='container'>
<h1>Home page 🚀</h1>
<nuxt-link to='/about'>About page</nuxt-link>
</div>
}
}

View File

@ -17,14 +17,14 @@ body {
}
.layout-enter-active, .layout-leave-active {
transition: opacity .5s
transition: opacity 0.5s
}
.layout-enter, .layout-leave-active {
opacity: 0
}
.bounce-enter-active {
animation: bounce-in .8s;
animation: bounce-in .5s;
}
.bounce-leave-active {
animation: bounce-out .5s;

View File

@ -1,11 +1,6 @@
<template>
<div>
<menu>
<ul>
<li>Option 1</li>
<li>Option 2</li>
</ul>
</menu>
<h1>Secondary Layout</h1>
<nuxt/>
</div>
</template>

View File

@ -5,7 +5,7 @@
"nuxt": "latest"
},
"scripts": {
"dev": "../../bin/nuxt",
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start"
}

View File

@ -3,5 +3,6 @@
<h1>Home page</h1>
<p><nuxt-link to="/about">About page</nuxt-link></p>
<p><nuxt-link to="/users">Lists of users</nuxt-link></p>
<p><nuxt-link to="/users-2">Lists of users #2 (with `watch`)</nuxt-link></p>
</div>
</template>

View File

@ -0,0 +1,91 @@
<template>
<div class="container">
<nuxt-link v-if="page > 1" :to="'?page=' + (page - 1)">&lt; Prev</nuxt-link>
<a v-else class="disabled">&lt; Prev</a>
<span>{{ page }}/{{ totalPages }}</span>
<nuxt-link v-if="page < totalPages" :to="'?page=' + (page + 1)">Next &gt;</nuxt-link>
<a v-else class="disabled">Next &gt;</a>
<transition mode="out-in" :name="transitionName">
<ul :key="page">
<li v-for="user in users" :key="user.id">
<img :src="user.avatar" class="avatar" />
<span>{{ user.first_name }} {{ user.last_name }}</span>
</li>
</ul>
</transition>
<p><nuxt-link to="/">Back home</nuxt-link></p>
</div>
</template>
<script>
import axios from 'axios'
export default {
watch: {
'$route.query.page': async function (page) {
this.$nuxt.$loading.start()
const { data } = await axios.get(`https://reqres.in/api/users?page=${page}`)
this.users = data.data
this.transitionName = this.getTransitionName(page)
this.page = +(page || 1)
this.totalPages = data.total_pages
this.$nuxt.$loading.finish()
}
},
async asyncData({ query }) {
const page = +(query.page || 1)
const { data } = await axios.get(`https://reqres.in/api/users?page=${page}`)
return {
page,
totalPages: data.total_pages,
users: data.data
}
},
data() {
return {
transitionName: this.getTransitionName(this.page)
}
},
methods: {
getTransitionName(newPage) {
return newPage < this.page ? 'slide-right' : 'slide-left'
}
}
}
</script>
<style scoped>
a {
display: inline-block;
margin: 0 1em;
color: #34495e;
text-decoration: none;
}
a.disabled {
color: #ccc;
}
ul {
margin: auto;
padding: 0;
width: 100%;
max-width: 400px;
padding-top: 40px;
transition: all .5s cubic-bezier(.55,0,.1,1);
}
li {
list-style-type: none;
width: 400px;
border: 1px #ddd solid;
overflow: hidden;
}
li img {
float: left;
width: 100px;
height: 100px;
}
li span {
display: inline-block;
padding-top: 40px;
text-transform: uppercase;
}
</style>

View File

@ -6,7 +6,7 @@
<nuxt-link v-if="page < totalPages" :to="'?page=' + (page + 1)">Next &gt;</nuxt-link>
<a v-else class="disabled">Next &gt;</a>
<ul>
<li v-for="user in users">
<li v-for="user in users" :key="user.id">
<img :src="user.avatar" class="avatar" />
<span>{{ user.first_name }} {{ user.last_name }}</span>
</li>
@ -19,15 +19,20 @@
import axios from 'axios'
export default {
transition (to, from) {
// Watch for $route.query.page to call Component methods (asyncData, fetch, validate, layout, etc.)
watchQuery: ['page'],
// Key for <nuxt-child> (transitions)
key: (to) => to.fullPath,
// Called to know which transition to apply
transition(to, from) {
if (!from) return 'slide-left'
return +to.query.page < +from.query.page ? 'slide-right' : 'slide-left'
},
async asyncData ({ query }) {
const page = query.page || 1
async asyncData({ query }) {
const page = +(query.page || 1)
const { data } = await axios.get(`https://reqres.in/api/users?page=${page}`)
return {
page: +data.page,
page,
totalPages: data.total_pages,
users: data.data
}

View File

@ -0,0 +1,5 @@
# Markdown Example
> Convert Markdown file to HTML using markdown-it.
**See [Markdownit Module](https://github.com/nuxt-community/modules/tree/master/packages/markdownit) for easy integration with [Nuxt.js](https://nuxtjs.org).**

View File

@ -0,0 +1,8 @@
module.exports = {
modules: [
'@nuxtjs/markdownit'
],
plugins: [
'~/plugins/md-it'
]
}

View File

@ -0,0 +1,17 @@
{
"name": "nuxt-markdownit",
"version": "1.0.0",
"dependencies": {
"@nuxtjs/markdownit": "^1.1.2",
"nuxt": "latest",
"pug": "^2.0.0-rc.4"
},
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start"
},
"devDependencies": {
"jstransformer-markdown-it": "^2.0.0"
}
}

View File

@ -0,0 +1,6 @@
<template lang="md">
# About Page!
Current route is: {{ $route.name }}
<nuxt-link to="/">Back home</nuxt-link>
</template>

View File

@ -0,0 +1,21 @@
<template lang="md">
# Hello World!
Current route is: {{ $route.path }}
Data model is: {{ model }}
<nuxt-link to="/about">Goto About</nuxt-link>
<nuxt-link to="/pug">Goto Pug</nuxt-link>
</template>
<script>
export default {
data() {
return {
model: 'I am index'
}
}
}
</script>

View File

@ -0,0 +1,20 @@
<template lang="pug">
div
h1 Pug Page
:markdown-it()
## Current route is: {{ $route.name }}
div(v-html="$md.render(model)")
br
nuxt-link(to='/') Back Home
</template>
<script>
export default {
data() {
return {
model: '## Title h2\n### title h3\n\nLong text Long text Long text Long text Long text Long text Long text Long text Long text \n\n* gimme a list item\n* and one more yeehaw'
}
}
}
</script>

View File

@ -0,0 +1,5 @@
import MarkdownIt from 'markdown-it'
export default ({ app }, inject) => {
inject('md', new MarkdownIt())
}

View File

@ -0,0 +1,13 @@
# Manage your app's meta information
Nuxt.js uses [vue-meta](https://github.com/declandewet/vue-meta) to manage page meta info (such as: meta, title, link, style, script) of your application.
## Example
SEO: https://nuxtjs.org/examples/seo-html-head
## Documentation
Nuxt.js: https://nuxtjs.org/guide/views#html-head
vue-meta: https://github.com/declandewet/vue-meta#table-of-contents

View File

@ -11,6 +11,12 @@ export default {
title: 'Home page 🚀',
meta: [
{ hid: 'description', name: 'description', content: 'Home page description' }
],
script: [
{ src: '/head.js' },
// Supported since 1.0
{ src: '/body.js', body: true },
{ src: '/defer.js', defer: '' }
]
}
}

View File

@ -0,0 +1 @@
console.log('about.js loaded!') // eslint-disable-line no-console

View File

@ -0,0 +1 @@
console.log('body.js loaded!') // eslint-disable-line no-console

View File

@ -0,0 +1 @@
console.log('defer.js loaded!') // eslint-disable-line no-console

View File

@ -0,0 +1 @@
console.log('head.js loaded!') // eslint-disable-line no-console

View File

@ -1,18 +1,18 @@
<template>
<ul>
<li v-for="visit in visits"><i>{{ visit.date | hours }}</i> - {{ visit.path }}</li>
<li v-for="(visit, index) in visits" :key="index"><i>{{ visit.date | hours }}</i> - {{ visit.path }}</li>
</ul>
</template>
<script>
export default {
computed: {
visits () {
visits() {
return this.$store.state.visits.slice().reverse()
}
},
filters: {
hours (date) {
hours(date) {
return date.split('T')[1].split('.')[0]
}
}

View File

@ -1,3 +1,3 @@
export default function (context) {
context.userAgent = context.isServer ? context.req.headers['user-agent'] : navigator.userAgent
context.userAgent = process.server ? context.req.headers['user-agent'] : navigator.userAgent
}

View File

@ -4,14 +4,16 @@
<pre>{{ userAgent }}</pre>
<ul>
<li><nuxt-link to="/">Home</nuxt-link></li>
<li v-for="slug in slugs"><nuxt-link :to="{ name: 'slug', params: { slug } }">{{ slug }}</nuxt-link></li>
<li v-for="(slug, index) in slugs" :key="index">
<nuxt-link :to="{ name: 'slug', params: { slug } }">{{ slug }}</nuxt-link>
</li>
</ul>
</div>
</template>
<script>
export default {
asyncData ({ store, route, userAgent }) {
asyncData({ store, route, userAgent }) {
return {
userAgent,
slugs: [

View File

@ -3,7 +3,7 @@ export const state = () => ({
})
export const mutations = {
ADD_VISIT (state, path) {
ADD_VISIT(state, path) {
state.visits.push({
path,
date: new Date().toJSON()

View File

@ -3,7 +3,7 @@
<div class="left">
<h2><nuxt-link to="/">Players</nuxt-link></h2>
<ul class="players">
<li v-for="user in users">
<li v-for="user in users" :key="user.id">
<nuxt-link :to="'/'+user.id">{{ user.name }}</nuxt-link>
</li>
</ul>
@ -16,7 +16,7 @@
<script>
export default {
asyncData ({ env }) {
asyncData({ env }) {
return { users: env.users }
}
}

View File

@ -7,17 +7,17 @@
<script>
export default {
validate ({ params }) {
validate({ params }) {
return !isNaN(+params.id)
},
asyncData ({ params, env, error }) {
asyncData({ params, env, error }) {
const user = env.users.find((user) => String(user.id) === params.id)
if (!user) {
return error({ message: 'User not found', statusCode: 404 })
}
return user
},
head () {
head() {
return {
title: this.name
}

View File

@ -9,7 +9,7 @@
import axios from 'axios'
export default {
asyncData () {
asyncData() {
const nb = Math.max(1, Math.round(Math.random() * 10))
return axios.get(`https://jsonplaceholder.typicode.com/photos/${nb}`).then(res => res.data)
}

View File

@ -12,7 +12,7 @@ if (process.browser) {
}
export default {
mounted () {
mounted() {
miniToastr.init()
},
notifications: {

View File

@ -6,7 +6,7 @@
<nuxt-link v-if="page < totalPages" :to="'?page=' + (page + 1)">Next &gt;</nuxt-link>
<a v-else class="disabled">Next &gt;</a>
<ul>
<li v-for="user in users">
<li v-for="user in users" :key="user.id">
<img :src="user.avatar" class="avatar" />
<span>{{ user.first_name }} {{ user.last_name }}</span>
</li>
@ -19,11 +19,11 @@
import axios from 'axios'
export default {
transition (to, from) {
transition(to, from) {
if (!from) return 'slide-left'
return +to.query.page < +from.query.page ? 'slide-right' : 'slide-left'
},
async asyncData ({ query }) {
async asyncData({ query }) {
const page = +query.page || 1
const { data } = await axios.get(`https://reqres.in/api/users?page=${page}`)
return {

View File

@ -7,9 +7,9 @@
<script>
export default {
asyncData ({ isServer }) {
asyncData() {
return {
name: (isServer ? 'server' : 'client')
name: (process.server ? 'server' : 'client')
}
}
}

View File

@ -9,7 +9,7 @@
<script>
export default {
asyncData ({ req }) {
asyncData({ req }) {
return {
name: req ? 'server' : 'client'
}

View File

@ -0,0 +1,3 @@
# Using build.styleResources with Nuxt.js
https://nuxtjs.org/examples

View File

@ -0,0 +1 @@
$main: #ccc;

View File

@ -0,0 +1,9 @@
module.exports = {
build: {
styleResources: {
patterns: [
'./assets/resources.scss'
]
}
}
}

Some files were not shown because too many files have changed in this diff Show More