├── .babelrc
├── .eslintignore
├── .eslintrc
├── .github
└── ISSUE_TEMPLATE.md
├── .gitignore
├── .vscode
└── launch.json
├── LICENSE
├── README.md
├── appveyor.yml
├── circle.yml
├── dev
├── .eslintrc
├── dist
│ ├── build-react.js
│ └── build-vue.js
├── vue.component.js
├── vue.js
├── vue.md
├── vue.options.js
└── vue.render.js
├── docs
├── LANGS.md
├── assets
│ ├── CNAME
│ └── circle.yml
├── book.json
├── deploy.sh
├── en
│ ├── README.md
│ ├── SUMMARY.md
│ ├── configurations
│ │ ├── advanced.md
│ │ ├── asset-url.md
│ │ ├── custom-blocks.md
│ │ ├── extract-css.md
│ │ └── pre-processors.md
│ ├── features
│ │ ├── css-modules.md
│ │ ├── es2015.md
│ │ ├── hot-reload.md
│ │ ├── postcss.md
│ │ └── scoped-css.md
│ ├── options.md
│ ├── start
│ │ ├── setup.md
│ │ └── spec.md
│ └── workflow
│ │ ├── linting.md
│ │ ├── production.md
│ │ ├── testing-with-mocks.md
│ │ └── testing.md
├── ja
│ ├── README.md
│ ├── SUMMARY.md
│ ├── configurations
│ │ ├── advanced.md
│ │ ├── asset-url.md
│ │ ├── custom-blocks.md
│ │ ├── extract-css.md
│ │ └── pre-processors.md
│ ├── features
│ │ ├── css-modules.md
│ │ ├── es2015.md
│ │ ├── hot-reload.md
│ │ ├── postcss.md
│ │ └── scoped-css.md
│ ├── options.md
│ ├── start
│ │ ├── setup.md
│ │ └── spec.md
│ └── workflow
│ │ ├── linting.md
│ │ ├── production.md
│ │ ├── testing-with-mocks.md
│ │ └── testing.md
├── kr
│ ├── README.md
│ ├── SUMMARY.md
│ ├── configurations
│ │ ├── advanced.md
│ │ ├── asset-url.md
│ │ ├── custom-blocks.md
│ │ ├── extract-css.md
│ │ └── pre-processors.md
│ ├── features
│ │ ├── css-modules.md
│ │ ├── es2015.md
│ │ ├── hot-reload.md
│ │ ├── postcss.md
│ │ └── scoped-css.md
│ ├── options.md
│ ├── start
│ │ ├── setup.md
│ │ └── spec.md
│ └── workflow
│ │ ├── linting.md
│ │ ├── production.md
│ │ ├── testing-with-mocks.md
│ │ └── testing.md
├── pt_BR
│ ├── README.md
│ ├── SUMMARY.md
│ ├── configurations
│ │ ├── advanced.md
│ │ ├── asset-url.md
│ │ ├── custom-blocks.md
│ │ ├── extract-css.md
│ │ └── pre-processors.md
│ ├── features
│ │ ├── css-modules.md
│ │ ├── es2015.md
│ │ ├── hot-reload.md
│ │ ├── postcss.md
│ │ └── scoped-css.md
│ ├── options.md
│ ├── start
│ │ ├── setup.md
│ │ └── spec.md
│ └── workflow
│ │ ├── linting.md
│ │ ├── production.md
│ │ ├── testing-with-mocks.md
│ │ └── testing.md
├── ru
│ ├── README.md
│ ├── SUMMARY.md
│ ├── configurations
│ │ ├── advanced.md
│ │ ├── asset-url.md
│ │ ├── custom-blocks.md
│ │ ├── extract-css.md
│ │ └── pre-processors.md
│ ├── features
│ │ ├── css-modules.md
│ │ ├── es2015.md
│ │ ├── hot-reload.md
│ │ ├── postcss.md
│ │ └── scoped-css.md
│ ├── options.md
│ ├── start
│ │ ├── setup.md
│ │ └── spec.md
│ └── workflow
│ │ ├── linting.md
│ │ ├── production.md
│ │ ├── testing-with-mocks.md
│ │ └── testing.md
└── zh-cn
│ ├── README.md
│ ├── SUMMARY.md
│ ├── configurations
│ ├── advanced.md
│ ├── asset-url.md
│ ├── custom-blocks.md
│ ├── extract-css.md
│ └── pre-processors.md
│ ├── features
│ ├── css-modules.md
│ ├── es2015.md
│ ├── hot-reload.md
│ ├── postcss.md
│ └── scoped-css.md
│ ├── options.md
│ ├── start
│ ├── setup.md
│ └── spec.md
│ └── workflow
│ ├── linting.md
│ ├── production.md
│ ├── testing-with-mocks.md
│ └── testing.md
├── index.js
├── lib
├── getRequireModule
│ └── index.js
├── loader.js
├── parser.js
├── script-compiler
│ ├── index.js
│ └── modules
│ │ └── parser.js
├── selector.js
├── style-compiler
│ ├── index.js
│ ├── load-postcss-config.js
│ └── plugins
│ │ ├── scope-id.js
│ │ └── trim.js
├── template-compiler
│ ├── index.js
│ ├── modules
│ │ └── transform-require.js
│ ├── plugins
│ │ └── addvm.js
│ └── preprocessor.js
└── utils
│ ├── gen-id.js
│ ├── normalize.js
│ ├── output-file.js
│ └── try-require.js
├── package.json
├── server.js
├── test
├── fixtures
│ ├── basic.vue
│ ├── css-modules.vue
│ ├── custom-blocks.vue
│ ├── custom-import.vue
│ ├── custom-language.vue
│ ├── custom-module.js
│ ├── custom-module.vue
│ ├── custom-options.vue
│ ├── es2015.vue
│ ├── extend.vue
│ ├── extract-css.vue
│ ├── functional-style.vue
│ ├── inject.js
│ ├── inject.vue
│ ├── logo.png
│ ├── markdown.vue
│ ├── media-query.vue
│ ├── postcss.vue
│ ├── pre.vue
│ ├── resolve.vue
│ ├── scoped-css.vue
│ ├── script-import.js
│ ├── script-import.vue
│ ├── service.js
│ ├── ssr-style.js
│ ├── ssr-style.vue
│ ├── style-import-scoped.css
│ ├── style-import.css
│ ├── style-import.vue
│ ├── template-import.pug
│ ├── template-import.vue
│ ├── transform.vue
│ └── unit-test.js
├── mock-loaders
│ ├── blog.js
│ ├── css.js
│ ├── docs.js
│ ├── html.js
│ ├── i18n.js
│ ├── js.js
│ └── yaml.js
└── test.js
└── yarn.lock
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": ["es2015"]
3 | }
4 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SmallComfort/react-vue-loader/c9af7291cac69083b4711156780f3135d0ff1063/.eslintignore
--------------------------------------------------------------------------------
/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "root": true,
3 | "extends": "vue"
4 | }
5 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | npm-debug.log
3 | test/output
4 | docs/_book
5 | .DS_Store
6 | .idea
7 | *.iml
8 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to learn about possible Node.js debug attributes.
3 | // Hover to view descriptions of existing attributes.
4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "type": "node",
9 | "request": "launch",
10 | "name": "启动程序",
11 | "program": "${workspaceRoot}/server.js"
12 | },
13 | {
14 | "type": "node",
15 | "request": "attach",
16 | "name": "附加到端口",
17 | "address": "localhost",
18 | "port": 5858
19 | }
20 | ]
21 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2015-present Yuxi (Evan) You
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-vue-loader
2 |
3 | A fork of vue-loader, use to compile the vue component into a react component.
4 |
5 | ## Install
6 | ```
7 | npm install --save react-vue react-vue-helper
8 | npm install --save-dev react-vue-loader
9 | ```
10 |
11 | ## Usage
12 | One possible configuration is as follows:
13 | ```javascript
14 | module: {
15 | rules: [
16 | {
17 | test: /\.vue$/,
18 | loader: 'react-vue-loader'
19 | }
20 | ]
21 | }
22 | ```
23 | [demo](https://github.com/SmallComfort/react-vue-demo)
24 |
25 | It supports almost all configurations of [vue-loader](https://vue-loader.vuejs.org). If you have used vue-loader, in most cases you only need to change your loader configuration ```loader: 'vue-loader'``` to ```loader: 'react-vue-loader'```. Refer to the [vue-loader](https://vue-loader.vuejs.org) for detailed configuration.
26 |
27 | ### Some Difference
28 |
29 | * react-vue-loader does not support [custom blocks](https://vue-loader.vuejs.org/en/configurations/custom-blocks.html)
30 |
31 | * Use [react-hot-loader](https://github.com/gaearon/react-hot-loader) to achieve hot reload
32 |
33 | * react-vue-loader adds additional options: ```vue```, ```output```
34 |
35 |
36 | ### Additional Options
37 |
38 | #### ```vue```
39 | * type: ```String```
40 |
41 | Used to import a global vue configuration. The loader will load the configuration and apply it to each vue component.
42 |
43 | ```javascript
44 | // vue.config.js
45 | import Vue from 'react-vue';
46 | import Vuex from 'vuex';
47 | import VueMaterial from 'vue-material/src'
48 |
49 | Vue.use(Vuex);
50 | Vue.use(VueMaterial);
51 |
52 | export default Vue;
53 | ```
54 |
55 | ```javascript
56 | module: {
57 | rules: [
58 | {
59 | test: /\.vue$/,
60 | loader: 'react-vue-loader',
61 | options: {
62 | vue: './vue.config.js'
63 | }
64 | }
65 | ]
66 | }
67 | ```
68 |
69 | #### ```output```
70 | * type: ```[Boolean, String]```
71 | * default: ```false```
72 |
73 | > Be cautious, it just creates a file and can not remove the file later, when you may want to delete one by one.
74 |
75 | Set ```true``` to see how the vue code is compiled into the react code, which will generate four js files in the same directory. To customize the generated file name, set a string type for ```output```
76 |
77 | ```javascript
78 | module: {
79 | rules: [
80 | {
81 | test: /\.vue$/,
82 | loader: 'react-vue-loader',
83 | options: {
84 | output: true
85 | // output: 'custome-name'
86 | }
87 | }
88 | ]
89 | }
90 | ```
91 |
92 |
93 | ## License
94 |
95 | [MIT](http://opensource.org/licenses/MIT)
96 |
--------------------------------------------------------------------------------
/appveyor.yml:
--------------------------------------------------------------------------------
1 | # Test against the latest version of this Node.js version
2 | environment:
3 | nodejs_version: "6"
4 |
5 | # Install scripts. (runs after repo cloning)
6 | install:
7 | # Get the latest stable version of Node.js or io.js
8 | - ps: Install-Product node $env:nodejs_version
9 | # install modules
10 | - npm install
11 |
12 | # Post-install test scripts.
13 | test_script:
14 | # Output useful info for debugging.
15 | - node --version
16 | - npm --version
17 | # run tests
18 | - npm test
19 |
20 | # Don't actually build.
21 | build: off
22 |
--------------------------------------------------------------------------------
/circle.yml:
--------------------------------------------------------------------------------
1 | machine:
2 | node:
3 | version: 6
4 |
--------------------------------------------------------------------------------
/dev/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "rules": {
3 | "space-before-function-paren": 0,
4 | "quotes": 0,
5 | "semi": 0,
6 | "comma-dangle": 0,
7 | "operator-linebreak": 0,
8 | "eol-last": 0,
9 | "camelcase": 0
10 | }
11 | }
--------------------------------------------------------------------------------
/dev/vue.component.js:
--------------------------------------------------------------------------------
1 | import Vue, {
2 | observer
3 | } from 'react-vue'
4 |
5 | import {
6 | Component
7 | } from 'react'
8 |
9 | import PropTypes from 'prop-types'
10 |
11 | import {
12 | buildComponent,
13 | platformDirectives
14 | } from 'react-vue-helper'
15 | import VueConfiger from "../index.js"
16 | export default (render, options, cssModules) => {
17 | return observer(
18 | class Vue extends buildComponent(
19 | render, Object.assign({}, {
20 | directives: platformDirectives
21 | }, options), {
22 | Component,
23 | PropTypes,
24 | Vue,
25 | cssModules,
26 | VueConfiger
27 | }
28 | ) {}
29 | )
30 | }
--------------------------------------------------------------------------------
/dev/vue.js:
--------------------------------------------------------------------------------
1 | require("!!style-loader!css-loader!../lib/style-compiler/index?{\"vue\":true,\"id\":\"data-v-78b356af\",\"scoped\":false,\"hasInlineConfig\":false}!../lib/selector?type=styles&index=0!./vue.md");
2 |
3 | var render = require("!!babel-loader!../lib/utils/output-file?{\"output\":\"\",\"type\":\"render\"}!../lib/template-compiler/index?{\"id\":\"data-v-78b356af\",\"scoped\":false}!../lib/selector?type=template&index=0!./vue.md").default;
4 |
5 | var options = require("!!babel-loader!../lib/utils/output-file?{\"output\":\"\",\"type\":\"options\"}!../lib/selector?type=script&index=0!./vue.md");
6 | options = options.default || options;
7 |
8 | var build = require("!!babel-loader!../lib/utils/output-file?{\"output\":\"\",\"type\":\"component\"}!../lib/script-compiler/index?{\"name\":\"vue\",\"vue\":\"./index.js\"}!../lib/selector?type=script&index=0!./vue.md").default;
9 |
10 | var Component = build(render, Object.assign({}, options, {
11 | __file: "/Users/smallcomfort/Desktop/study/vue-loader/dev/vue.md"
12 | }));
13 |
14 | module.exports = Component;
--------------------------------------------------------------------------------
/dev/vue.options.js:
--------------------------------------------------------------------------------
1 | var iconList = require('examples/icon.json');
2 |
3 | export default {
4 | data() {
5 | return {
6 | icons: iconList
7 | };
8 | }
9 | }
--------------------------------------------------------------------------------
/docs/LANGS.md:
--------------------------------------------------------------------------------
1 | * [English](en/)
2 | * [한국어](kr/)
3 | * [Русский](ru/)
4 | * [Português](pt_BR/)
5 | * [日本語](ja/)
6 | * [中文](zh-cn/)
7 |
--------------------------------------------------------------------------------
/docs/assets/CNAME:
--------------------------------------------------------------------------------
1 | vue-loader.vuejs.org
2 |
--------------------------------------------------------------------------------
/docs/assets/circle.yml:
--------------------------------------------------------------------------------
1 | general:
2 | branches:
3 | ignore:
4 | - gh-pages
5 |
--------------------------------------------------------------------------------
/docs/book.json:
--------------------------------------------------------------------------------
1 | {
2 | "gitbook": ">3.0.0",
3 | "plugins": ["edit-link", "theme-vuejs@git+https://github.com/pearofducks/gitbook-plugin-theme-vuejs.git", "-fontsettings", "github"],
4 | "pluginsConfig": {
5 | "edit-link": {
6 | "base": "https://github.com/vuejs/vue-loader/tree/master/docs",
7 | "label": "Edit This Page"
8 | },
9 | "github": {
10 | "url": "https://github.com/vuejs/vue-loader/"
11 | }
12 | },
13 | "links": {
14 | "sharing": {
15 | "facebook": false,
16 | "twitter": false
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/docs/deploy.sh:
--------------------------------------------------------------------------------
1 | cd docs
2 | rm -rf _book
3 | gitbook build
4 | cp assets/circle.yml _book/circle.yml
5 | cp assets/CNAME _book/CNAME
6 | cd _book
7 | git init
8 | git add -A
9 | git commit -m 'update book'
10 | git push -f git@github.com:vuejs/vue-loader.git master:gh-pages
11 |
--------------------------------------------------------------------------------
/docs/en/README.md:
--------------------------------------------------------------------------------
1 | # Introduction
2 |
3 | ### What is `vue-loader`?
4 |
5 | `vue-loader` is a loader for Webpack that can transform Vue components written in the following format into a plain JavaScript module:
6 |
7 | 
8 |
9 | There are many cool features provided by `vue-loader`:
10 |
11 | - ES2015 enabled by default;
12 | - Allows using other Webpack loaders for each part of a Vue component, for example SASS for `
17 | ```
18 |
19 | Under the hood, the text content inside the `
79 | ```
80 |
81 | However, note this makes your Vue component Webpack-specific and not compatible with Browserify and [vueify](https://github.com/vuejs/vueify). **If you intend to ship your Vue component as a reusable 3rd-party component, avoid using this syntax.**
82 |
--------------------------------------------------------------------------------
/docs/en/features/es2015.md:
--------------------------------------------------------------------------------
1 | # ES2015
2 |
3 | When `vue-loader` detects the presence of `babel-loader` or `buble-loader` in the same project, it will use them to process the `
23 | ```
24 |
25 | We are using ES2015's Object literal shorthand here to define the child components. `{ ComponentA }` is simply shorthand for `{ ComponentA: ComponentA }`. Vue will automatically convert the key to `component-a`, so you can use the imported component in the template as ``.
26 |
27 | ### ES2015 in Templates
28 |
29 | `` in `*.vue` files are compiled into JavaScript render functions and then processed by a custom build of [Buble](https://buble.surge.sh/guide/) to support ES2015 features. This allows you to use features such as [Object shorthand properties](https://buble.surge.sh/guide/#object-shorthand-methods-and-properties-transforms-concisemethodproperty-) and [computed properties](https://buble.surge.sh/guide/#computed-properties-transforms-computedproperty-):
30 |
31 | ``` html
32 |
33 | ```
34 |
35 | can be simplified to:
36 |
37 | ``` html
38 |
39 | ```
40 |
41 | **vue@^2.1.0 only:** You can even use parameter destructuring with `v-for` or scoped slots:
42 |
43 | ``` html
44 |
45 | {{ id }} {{ text }}
46 |
47 | ```
48 |
49 | ``` html
50 |
51 |
52 | {{ id }} {{ text }}
53 |
54 |
55 | ```
56 |
57 | You can also customize the features supported in templates using the [`buble` option](../options.md#buble).
58 |
59 | ### Transpiling Normal `.js` Files
60 |
61 | Since `vue-loader` only processes `*.vue` files, you'd need to tell Webpack to process normal `*.js` files with `babel-loader` or `buble-loader` in the Webpack config file. The project scaffolded with `vue-cli` already does it for you.
62 |
63 | ### Configuring Babel with `.babelrc`
64 |
65 | `babel-loader` respects [`.babelrc`](https://babeljs.io/docs/usage/babelrc/), so it is the recommended approach to configure the Babel presets and plugins.
66 |
--------------------------------------------------------------------------------
/docs/en/features/hot-reload.md:
--------------------------------------------------------------------------------
1 | # Hot Reload
2 |
3 | "Hot Reload" is not simply reloading the page when you edit a file. With hot reload enabled, when you edit a `*.vue` file, all instances of that component will be swapped in **without reloading the page**. It even preserves the current state of your app and these swapped components! This dramatically improves the development experience when you are tweaking the templates or styling of your components.
4 |
5 | 
6 |
7 | When scaffolding the project with `vue-cli`, Hot Reload is enabled out-of-the-box.
8 |
--------------------------------------------------------------------------------
/docs/en/features/postcss.md:
--------------------------------------------------------------------------------
1 | # PostCSS
2 |
3 | Any CSS output processed by `vue-loader` is piped through [PostCSS](https://github.com/postcss/postcss) for scoped CSS rewriting. You can also add custom PostCSS plugins to the process, for example [autoprefixer](https://github.com/postcss/autoprefixer) or [CSSNext](http://cssnext.io/).
4 |
5 | ## Using a Config File
6 |
7 | Starting in 11.0 `vue-loader` supports auto-loading the same PostCss config files supported by [`postcss-loader`](https://github.com/postcss/postcss-loader#usage):
8 |
9 | - `postcss.config.js`
10 | - `.postcssrc`
11 | - `postcss` field in `package.json`
12 |
13 | Using a config file allows you to share the same config between your normal CSS files processed by `postcss-loader` and the CSS inside `*.vue` files, and is recommended.
14 |
15 | ## Inline Options
16 |
17 | Alternatively, you can specify postcss config specifically for `*.vue` files using the `postcss` option for `vue-loader`.
18 |
19 | Example usage in Webpack 1.x:
20 |
21 | ``` js
22 | // webpack.config.js
23 | module.exports = {
24 | // other configs...
25 | vue: {
26 | // use custom postcss plugins
27 | postcss: [require('postcss-cssnext')()]
28 | }
29 | }
30 | ```
31 |
32 | For Webpack 2.x:
33 |
34 | ``` js
35 | // webpack.config.js
36 | module.exports = {
37 | // other options...
38 | module: {
39 | // module.rules is the same as module.loaders in 1.x
40 | rules: [
41 | {
42 | test: /\.vue$/,
43 | loader: 'vue-loader',
44 | // vue-loader options goes here
45 | options: {
46 | // ...
47 | postcss: [require('postcss-cssnext')()]
48 | }
49 | }
50 | ]
51 | }
52 | }
53 | ```
54 |
55 | In addition to providing an Array of plugins, the `postcss` option also accepts:
56 |
57 | - A function that returns an array of plugins;
58 |
59 | - An object that contains options to be passed to the PostCSS processor. This is useful when you are using PostCSS projects that relies on custom parser/stringifiers:
60 |
61 | ``` js
62 | postcss: {
63 | plugins: [...], // list of plugins
64 | options: {
65 | parser: sugarss // use sugarss parser
66 | }
67 | }
68 | ```
69 |
--------------------------------------------------------------------------------
/docs/en/features/scoped-css.md:
--------------------------------------------------------------------------------
1 | # Scoped CSS
2 |
3 | When a `
11 |
12 |
13 |
hi
14 |
15 | ```
16 |
17 | Into the following:
18 |
19 | ``` html
20 |
25 |
26 |
27 |
hi
28 |
29 | ```
30 |
31 | #### Notes
32 |
33 | 1. You can include both scoped and non-scoped styles in the same component:
34 |
35 | ``` html
36 |
39 |
40 |
43 | ```
44 |
45 | 2. A child component's root node will be affected by both the parent's scoped CSS and the child's scoped CSS.
46 |
47 | 3. Partials are not affected by scoped styles.
48 |
49 | 4. **Scoped styles do not eliminate the need for classes**. Due to the way browsers render various CSS selectors, `p { color: red }` will be many times slower when scoped (i.e. when combined with an attribute selector). If you use classes or ids instead, such as in `.example { color: red }`, then you virtually eliminate that performance hit. [Here's a playground](http://stevesouders.com/efws/css-selectors/csscreate.php) where you can test the differences yourself.
50 |
51 | 5. **Be careful with descendant selectors in recursive components!** For a CSS rule with the selector `.a .b`, if the element that matches `.a` contains a recursive child component, then all `.b` in that child component will be matched by the rule.
52 |
--------------------------------------------------------------------------------
/docs/en/start/setup.md:
--------------------------------------------------------------------------------
1 | # Setting Up a Project
2 |
3 | ### Using `vue-cli`
4 |
5 | It's recommended to scaffold a project using `vue-loader` with `vue-cli`:
6 |
7 | ``` bash
8 | npm install -g vue-cli
9 | vue init webpack-simple hello-vue
10 | cd hello-vue
11 | npm install
12 | npm run dev # ready to go!
13 | ```
14 |
--------------------------------------------------------------------------------
/docs/en/workflow/linting.md:
--------------------------------------------------------------------------------
1 | # Linting
2 |
3 | You may have been wondering how do you lint your code inside `*.vue` files, since they are not JavaScript. We will assume you are using [ESLint](http://eslint.org/) (if you are not, you should!).
4 |
5 | You will also need the [eslint-plugin-html](https://github.com/BenoitZugmeyer/eslint-plugin-html) which supports extracting and linting the JavaScript inside `*.vue` files.
6 |
7 | Make sure to include the plugin in your ESLint config:
8 |
9 | ``` json
10 | "plugins": [
11 | "html"
12 | ]
13 | ```
14 |
15 | Then from the command line:
16 |
17 | ``` bash
18 | eslint --ext js,vue MyComponent.vue
19 | ```
20 |
21 | Another option is using [eslint-loader](https://github.com/MoOx/eslint-loader) so that your `*.vue` files are automatically linted on save during development:
22 |
23 | ``` bash
24 | npm install eslint eslint-loader --save-dev
25 | ```
26 |
27 | ``` js
28 | // webpack.config.js
29 | module.exports = {
30 | // ... other options
31 | module: {
32 | loaders: [
33 | {
34 | test: /.vue$/,
35 | loader: 'vue!eslint'
36 | }
37 | ]
38 | }
39 | }
40 | ```
41 |
42 | Note that Webpack loader chains are applied **right-first**. Make sure to apply `eslint` before `vue` so we are linting the pre-compile source code.
43 |
44 | One thing we need to consider is using third party `*.vue` components shipped in NPM packages. In such case, we want to use `vue-loader` to process the third party component, but do not want to lint it. We can separate the linting into Webpack's [preLoaders](https://webpack.github.io/docs/loaders.html#loader-order):
45 |
46 | ``` js
47 | // webpack.config.js
48 | module.exports = {
49 | // ... other options
50 | module: {
51 | // only lint local *.vue files
52 | preLoaders: [
53 | {
54 | test: /.vue$/,
55 | loader: 'eslint',
56 | exclude: /node_modules/
57 | }
58 | ],
59 | // but use vue-loader for all *.vue files
60 | loaders: [
61 | {
62 | test: /.vue$/,
63 | loader: 'vue'
64 | }
65 | ]
66 | }
67 | }
68 | ```
69 |
70 | For Webpack 2.x:
71 |
72 | ``` js
73 | // webpack.config.js
74 | module.exports = {
75 | // ... other options
76 | module: {
77 | rules: [
78 | // only lint local *.vue files
79 | {
80 | enforce: 'pre',
81 | test: /.vue$/,
82 | loader: 'eslint-loader',
83 | exclude: /node_modules/
84 | },
85 | // but use vue-loader for all *.vue files
86 | {
87 | test: /.vue$/,
88 | loader: 'vue-loader'
89 | }
90 | ]
91 | }
92 | }
93 | ```
94 |
--------------------------------------------------------------------------------
/docs/en/workflow/production.md:
--------------------------------------------------------------------------------
1 | # Production Build
2 |
3 | There are two things to do when building our bundle for production:
4 |
5 | 1. Minify our application code;
6 | 2. Use the [setup described in the Vue.js guide](https://vuejs.org/guide/deployment.html) to strip all the warnings from Vue.js source code.
7 |
8 | Here's an example config:
9 |
10 | ``` js
11 | // webpack.config.js
12 | module.exports = {
13 | // ... other options
14 | plugins: [
15 | // short-circuits all Vue.js warning code
16 | new webpack.DefinePlugin({
17 | 'process.env': {
18 | NODE_ENV: '"production"'
19 | }
20 | }),
21 | // minify with dead-code elimination
22 | new webpack.optimize.UglifyJsPlugin({
23 | compress: {
24 | warnings: false
25 | }
26 | }),
27 | // Webpack 1 only - optimize module ids by occurrence count
28 | new webpack.optimize.OccurrenceOrderPlugin()
29 | ]
30 | }
31 | ```
32 |
33 | Obviously we don't want to use this config during development, so there are several ways to approach this:
34 |
35 | 1. Dynamically build up the configuration object based on an environment variable;
36 |
37 | 2. Or, use two separate Webpack config files, one for development and one for production. And maybe share some common options between them in a third file, as shown in [vue-hackernews-2.0](https://github.com/vuejs/vue-hackernews-2.0).
38 |
39 | It's really up to you as long as it achieves the goal.
40 |
--------------------------------------------------------------------------------
/docs/en/workflow/testing-with-mocks.md:
--------------------------------------------------------------------------------
1 | # Testing with Mocks
2 |
3 | In a real world application, our components most likely have external dependencies. When writing unit tests for components, it would be ideal if we can mock these external dependencies so that our tests only rely the behavior of the component being tested.
4 |
5 | `vue-loader` provides a feature that allows you to inject arbitrary dependencies to a `*.vue` component, using [inject-loader](https://github.com/plasticine/inject-loader). The general idea is that instead of directly importing the component module, we use `inject-loader` to create a "module factory" function for that module. When this function gets called with an object of mocks, it returns an instance of the module with the mocks injected.
6 |
7 | Suppose we have a component like this:
8 |
9 | ``` html
10 |
11 |
12 |
{{ msg }}
13 |
14 |
15 |
27 | ```
28 |
29 | Here's how to import it with mocks:
30 |
31 | > Note: inject-loader@3.x is currently unstable.
32 |
33 | ``` bash
34 | npm install inject-loader@^2.0.0 --save-dev
35 | ```
36 |
37 | ``` js
38 | // example.spec.js
39 | const ExampleInjector = require('!!vue?inject!./example.vue')
40 | ```
41 |
42 | Notice that crazy require string - we are using some inline [webpack loader requests](https://webpack.github.io/docs/loaders.html) here. A quick explanation:
43 |
44 | - `!!` at the start means "disable all loaders from the global config";
45 | - `vue?inject!` means "use the `vue` loader, and pass in the `?inject` query". This tells `vue-loader` to compile the component in dependency-injection mode.
46 |
47 | The returned `ExampleInjector` is a factory function that can be called to create instances of the `example.vue` module:
48 |
49 | ``` js
50 | const ExampleWithMocks = ExampleInjector({
51 | // mock it
52 | '../service': {
53 | msg: 'Hello from a mocked service!'
54 | }
55 | })
56 | ```
57 |
58 | Finally, we can test the component like usual:
59 |
60 | ``` js
61 | it('should render', () => {
62 | const vm = new Vue({
63 | template: '
',
64 | components: {
65 | 'test': ExampleWithMocks
66 | }
67 | }).$mount()
68 | expect(vm.$el.querySelector('.msg').textContent).toBe('Hello from a mocked service!')
69 | })
70 | ```
71 |
--------------------------------------------------------------------------------
/docs/kr/README.md:
--------------------------------------------------------------------------------
1 | # 소개
2 |
3 | ### `vue-loader`는 무엇인가요?
4 |
5 | `vue-loader`는 다음과 같이 작성된 Vue 컴포넌트를 일반적인 자바스크립트 모듈로 변환할 수 있는 Webpack에서 사용하는 로더입니다.
6 |
7 | 
8 |
9 | 다음은 `vue-loader`가 제공하는 여러가지 유용한 기능입니다.
10 |
11 | - 기본적으로 ES2015를 지원합니다.
12 | - 각 Vue 컴포넌트 마다 서로 다른 Webpack 로더를 사용할 수 있습니다. 예를들면 `
39 | ```
40 |
41 | #### webpack.config.js
42 |
43 | ``` js
44 | // Webpack 2.x
45 | var ExtractTextPlugin = require("extract-text-webpack-plugin")
46 |
47 | module.exports = {
48 | module: {
49 | rules: [
50 | {
51 | test: /\.vue$/,
52 | loader: 'vue',
53 | options: {
54 | loaders: {
55 | // 모든 의 내용을 원문 그대로 추출합니다
56 | 'docs': ExtractTextPlugin.extract('raw-loader'),
57 | }
58 | }
59 | }
60 | ]
61 | },
62 | plugins: [
63 | // 모든 docs를 하나의 파일로 추출합니다
64 | new ExtractTextPlugin('docs.md')
65 | ]
66 | }
67 | ```
68 |
69 | ## 런타임에서 사용할 수 있는 문서
70 |
71 | 다음은 `` 사용자 정의 블록을 컴포넌트에 넣어 런타임에서 사용할 수 있는 예제입니다.
72 |
73 | #### docs-loader.js
74 |
75 | 사용자 정의 블록 콘텐트를 삽입하려면 사용자 정의 로더가 필요합니다.
76 |
77 | ``` js
78 | module.exports = function (source, map) {
79 | this.callback(null, 'module.exports = function(Component) {Component.options.__docs = ' +
80 | JSON.stringify(source) +
81 | '}', map)
82 | }
83 | ```
84 |
85 | #### webpack.config.js
86 |
87 | webpack이 `` 사용자 정의 블록을 위한 로더를 사용하도록 설정합니다.
88 |
89 | ``` js
90 | const docsLoader = require.resolve('./custom-loaders/docs-loader.js')
91 |
92 | module.exports = {
93 | module: {
94 | rules: [
95 | {
96 | test: /\.vue$/,
97 | loader: 'vue',
98 | options: {
99 | loaders: {
100 | 'docs': docsLoader
101 | }
102 | }
103 | }
104 | ]
105 | }
106 | }
107 | ```
108 |
109 | #### component.vue
110 |
111 | 이제 `` 블록의 내용을 런타임 중에 컴포넌트에서 사용할 수 있습니다.
112 |
113 | ``` html
114 |
115 |
116 |
117 |
{{ docs }}
118 |
119 |
120 |
121 |
133 | ```
134 |
--------------------------------------------------------------------------------
/docs/kr/configurations/extract-css.md:
--------------------------------------------------------------------------------
1 | # CSS 단일 파일로 추출하기
2 |
3 | ``` bash
4 | npm install extract-text-webpack-plugin --save-dev
5 | ```
6 |
7 | ## 쉬운 방법
8 |
9 | > vue-loader@^12.0.0와 webpack@^2.0.0 필요
10 |
11 | ``` js
12 | // webpack.config.js
13 | var ExtractTextPlugin = require("extract-text-webpack-plugin")
14 |
15 | module.exports = {
16 | // other options...
17 | module: {
18 | rules: [
19 | {
20 | test: /\.vue$/,
21 | loader: 'vue-loader',
22 | options: {
23 | extractCSS: true
24 | }
25 | }
26 | ]
27 | },
28 | plugins: [
29 | new ExtractTextPlugin("style.css")
30 | ]
31 | }
32 | ```
33 |
34 | 위 코드는 `*.vue` 파일 내부에서 `
17 | ```
18 |
19 | 내부적으로, `
60 | ```
61 |
62 | 그러나 이것은 Vue 컴포넌트가 Webpack에 한정되어 있고 Browserify 및 [vueify](https://github.com/vuejs/vueify)와 호환되지 않습니다. **Vue 컴포넌트를 재사용 가능한 써드파티로 제공하려면 이 구문을 사용하지 마십시오.**
63 |
--------------------------------------------------------------------------------
/docs/kr/features/css-modules.md:
--------------------------------------------------------------------------------
1 | # CSS 모듈
2 |
3 | > 9.8.0 이상 버전을 요구합니다
4 |
5 | [CSS 모듈](https://github.com/css-modules/css-modules)은 CSS을 모듈화하고 구성하는데 널리 사용되는 시스템입니다. `vue-loader`는 시뮬레이트된 범위 CSS의 대안으로 CSS 모듈과 함께 1급 클래스로의 통합을 제공합니다.
6 |
7 | ### 사용법
8 |
9 | `
20 | ```
21 |
22 | 이렇게하면 `css-loader`에 대한 CSS 모듈 모드가 켜지고 결과적으로 클래스 식별자 오브젝트는 `$style` 이름의 계산된 속성으로 컴포넌트에 주입됩니다. 동적 클래스 바인딩을 사용하여 템플릿에서 이를 사용할 수 있습니다.
23 |
24 | ``` html
25 |
26 |
27 | 이것은 빨간색이야
28 |
29 |
30 | ```
31 |
32 | 이는 계산된 속성이기 때문에 `:class`의 오브젝트/배열 문법에도 작동합니다.
33 |
34 | ``` html
35 |
36 |
37 |
38 | 나는 빨간색이야?
39 |
40 |
41 | 나는 빨간색이면서 볼드야
42 |
43 |
44 |
45 | ```
46 |
47 | 또한 JavaScript에서도 접근할 수 있습니다.
48 |
49 | ``` html
50 |
59 | ```
60 |
61 | [전역 예외사항](https://github.com/css-modules/css-modules#exceptions)과 [구성](https://github.com/css-modules/css-modules#composition) 같은 자세한 정보는 [CSS 모듈 스펙](https://github.com/css-modules/css-modules)을 참고하세요.
62 |
63 | ### 사용자 정의 이름 주입
64 |
65 | 하나의 `*.vue` 컴포넌트 내에 하나 이상의 `
71 |
72 |
75 | ```
76 |
77 | ### `css-loader` 쿼리 설정
78 |
79 | CSS 모듈은 [css-loader](https://github.com/webpack/css-loader)를 통해 처리됩니다. `
11 |
12 |
13 |
안녕
14 |
15 | ```
16 |
17 | 다음과 같이 변환됩니다.
18 |
19 | ``` html
20 |
25 |
26 |
27 |
안녕
28 |
29 | ```
30 |
31 | #### 참고사항
32 |
33 | 1. 범위가 지정된 스타일과 범위가 지정되지 않은 스타일은 동일한 컴포넌트에 포함 할 수 있습니다.
34 |
35 | ``` html
36 |
39 |
40 |
43 | ```
44 |
45 | 2. 하위 컴포넌트의 루트 노드는 상위 범위 CSS와 하위 범위 CSS의 영향을 받습니다.
46 |
47 | 3. Partial은 범위가 지정된 스타일의 영향을 받지 않습니다.
48 |
49 | 4. **범위가 지정된 스타일은 클래스의 필요성을 제거하는 것이 아닙니다**. 브라우저가 다양한 CSS 셀렉터를 렌더링하는 방식 때문에 `p { color: red }`는 범위(즉 속성 선택자와 결합될 때)가 지정될 때 몇 배는 더 느려집니다. `.example { color: red }`와 같이 클래스 또는 id를 대신 사용한다면 성능 이슈를 해결할 수 있습니다. [여기 플레이그라운드](http://stevesouders.com/efws/css-selectors/csscreate.php)에서 차이점을 테스트 할 수 있습니다.
50 |
51 | 5. **하위 컴포넌트의 선택자 사용을 조심하세요!** 선택자 `.a .b`가 있는 CSS 규칙의 경우 `.a`와 일치하는 요소에 하위 컴포넌트가 포함되어 있을 경우 해당 하위 컴포넌트의 모든 `.b`가 CSS 규칙에 적용됩니다.
52 |
--------------------------------------------------------------------------------
/docs/kr/start/setup.md:
--------------------------------------------------------------------------------
1 | # 프로젝트 세팅하기
2 |
3 | ### 구문 강조
4 |
5 | 먼저 `*.vue` 컴포넌트에 대한 올바른 구문 강조가 필요할 것입니다. 현재 [Sublime Text](https://github.com/vuejs/vue-syntax-highlight), [Atom](https://atom.io/packages/language-vue) 그리고 [Vim](https://github.com/posva/vim-vue) 등이 구문 강조를 지원합니다. 다른 에디터/IDE에 대한 컨트리뷰션은 매우 환영합니다! 만약 에디터/IDE에서 구문 강조를 지원하지 않고, Vue 컴포넌트에서 전처리기를 사용하지 않는 경우 에디터에서 `*.vue` 파일을 HTML 형태로 보는 것을 추천합니다.
6 |
7 | ### `vue-cli` 사용하기
8 |
9 | `vue-loader`와 `vue-cli`를 사용하여 프로젝트를 진행하는 것을 추천합니다.
10 |
11 | ``` bash
12 | npm install -g vue-cli
13 | vue init webpack-simple hello-vue
14 | cd hello-vue
15 | npm install
16 | npm run dev # 시작할 준비가 되었습니다!
17 | ```
18 |
--------------------------------------------------------------------------------
/docs/kr/workflow/linting.md:
--------------------------------------------------------------------------------
1 | # Linting
2 |
3 | `*.vue` 파일은 JavaScript가 아니기 때문에 내부 코드를 어떻게 lint하는지 궁금했을 겁니다. 우리는 당신이 [ESLint](http://eslint.org/)를 사용하고 있다고 가정합니다. (그렇지 않다면 사용해야합니다!)
4 |
5 | `*.vue` 파일 내에서 JavaScript를 추출하고 linting하는 것과 함께 [eslint-html-plugin](https://github.com/BenoitZugmeyer/eslint-plugin-html)이 필요합니다.
6 |
7 | 그리고 ESLint 설정에 플러그인을 포함해야 합니다.
8 |
9 | ``` json
10 | "plugins": [
11 | "html"
12 | ]
13 | ```
14 |
15 | 그 다음 커맨드 라인에서 다음과 같이 입력합니다.
16 |
17 | ``` bash
18 | eslint --ext js,vue MyComponent.vue
19 | ```
20 |
21 | 또 다른 옵션은 [eslint-loader](https://github.com/MoOx/eslint-loader)를 사용하여 개발 중에 `*.vue` 파일이 저장될 때 자동으로 lint할 수 있습니다.
22 |
23 | ``` bash
24 | npm install eslint eslint-loader --save-dev
25 | ```
26 |
27 | ``` js
28 | // webpack.config.js
29 | module.exports = {
30 | // 여기에 다른 옵션이 올 수 있습니다.
31 | module: {
32 | loaders: [
33 | {
34 | test: /.vue$/,
35 | loader: 'vue!eslint'
36 | }
37 | ]
38 | }
39 | }
40 | ```
41 |
42 | Webpack 로더 체인이 **가장 먼저** 적용됩니다. `vue` 전에 `eslint`를 적용하여 컴파일 전 소스코드를 lint하세요.
43 |
44 | 우리가 고려해야할 한 가지는 NPM 패키지에 포함 된 써드파티 `*.vue` 컴포넌트를 사용하는 것 입니다. 이 경우에 우리는 써드파티 컴포넌트를 처리하기 위해 `vue-loader`를 사용하려고 하지만 그것을 lint하고 싶지는 않습니다. 우리는 lint를 Webpack의 [preLoaders](https://webpack.github.io/docs/loaders.html#loader-order)로 분리할 수 있습니다.
45 |
46 | ``` js
47 | // webpack.config.js
48 | module.exports = {
49 | // 여기에 다른 옵션이 올 수 있습니다.
50 | module: {
51 | // 오직 로컬 *.vue 파일만 lint합니다.
52 | preLoaders: [
53 | {
54 | test: /.vue$/,
55 | loader: 'eslint',
56 | exclude: /node_modules/
57 | }
58 | ],
59 | // 하지만 모든 *.vue 파일에 대해 vue-loader를 사용하세요.
60 | loaders: [
61 | {
62 | test: /.vue$/,
63 | loader: 'vue'
64 | }
65 | ]
66 | }
67 | }
68 | ```
69 |
70 | Webpack 2.x에서는 다음과 같이 처리합니다.
71 |
72 | ``` js
73 | // webpack.config.js
74 | module.exports = {
75 | // 여기에 다른 옵션이 올 수 있습니다.
76 | module: {
77 | rules: [
78 | // 오직 로컬 *.vue 파일만 lint합니다.
79 | {
80 | enforce: 'pre',
81 | test: /.vue$/,
82 | loader: 'eslint',
83 | exclude: /node_modules/
84 | },
85 | // 하지만 모든 *.vue 파일에 대해 vue-loader를 사용하세요.
86 | {
87 | test: /.vue$/,
88 | loader: 'vue'
89 | }
90 | ]
91 | }
92 | }
93 | ```
94 |
--------------------------------------------------------------------------------
/docs/kr/workflow/production.md:
--------------------------------------------------------------------------------
1 | # 배포용 빌드
2 |
3 | 배포 환경을 위해 번들을 제작할 때는 다음 두 가지 작업을 수행해야 합니다.
4 |
5 | 1. 어플리케이션 코드를 최소화 합니다.
6 | 2. Vue.js 소스 코드의 모든 경고를 제거하려면 [Vue.js 가이드에 설명된 설정](https://vuejs.org/guide/deployment.html)을 사용하세요.
7 |
8 | 여기 예제 설정이 있습니다.
9 |
10 | ``` js
11 | // webpack.config.js
12 | module.exports = {
13 | // 여기에 다른 옵션이 올 수 있습니다.
14 | plugins: [
15 | // 모든 Vue.js 경고 코드를 숨깁니다.
16 | new webpack.DefinePlugin({
17 | 'process.env': {
18 | NODE_ENV: '"production"'
19 | }
20 | }),
21 | // 불필요한 코드를 제거하여 최소화 합니다.
22 | new webpack.optimize.UglifyJsPlugin({
23 | compress: {
24 | warnings: false
25 | }
26 | }),
27 | // 발생 횟수에 따라 모듈 ID를 최적화합니다.
28 | new webpack.optimize.OccurenceOrderPlugin()
29 | ]
30 | }
31 | ```
32 |
33 | 개발 중에는 이 설정을 사용하고 싶지 않으므로 이것을 해결하는 몇 가지 방법이 있습니다.
34 |
35 | 1. 환경변수 기반으로 설정 오브젝트를 동적으로 빌드할 수 있습니다.
36 |
37 | 2. 또는 개발용 Webpack 설정 파일과 배포용 설정 파일을 분리하여 사용합니다. 그리고 [vue-hackernews-2.0](https://github.com/vuejs/vue-hackernews-2.0)에 표시 된 것처럼 세 번째 파일에서 공통 옵션을 공유할 수도 있습니다.
38 |
39 | 당신에게 목표 달성이 달려있습니다.
40 |
--------------------------------------------------------------------------------
/docs/kr/workflow/testing-with-mocks.md:
--------------------------------------------------------------------------------
1 | # 목업을 위한 테스트
2 |
3 | 실제 애플리케이션에서는 컴포넌트에 외부 의존성이 있을 가능성이 큽니다. 컴포넌트에 대한 유닛 테스트를 작성할 때 테스트가 테스트 중인 컴포넌트의 동작에만 의존하도록 mock을 만드는 것이 이상적 입니다.
4 |
5 | `vue-loader`는 [inject-loader](https://github.com/plasticine/inject-loader)를 사용하여 임의의 의존성을 `*.vue` 컴포넌트에 주입 할 수 있는 기능을 제공합니다. 일반적인 아이디어로 컴포넌트 모듈을 직접 가져오는 대신 `inject-loader`를 사용하여 해당 모듈에 대한 "모듈 팩토리" 함수를 생성하는 것 입니다. 이 함수가 목업 객체와 함께 호출되면 목업 객체가 삽입된 모듈의 인스턴트를 반환합니다.
6 |
7 | 다음과 같은 컴포넌트가 있다고 가정해봅시다.
8 |
9 | ``` html
10 |
11 |
12 |
{{ msg }}
13 |
14 |
15 |
27 | ```
28 |
29 | 목업을 가져오는 방법은 다음과 같습니다.
30 |
31 | > 주의: `inject-loader@3.x`는 현재 불안정합니다.
32 |
33 | ``` bash
34 | npm install inject-loader@^2.0.0 --save-dev
35 | ```
36 |
37 | ``` js
38 | // example.spec.js
39 | const ExampleInjector = require('!!vue?inject!./example.vue')
40 | ```
41 |
42 | 위 코드의 require 문자열은 이상해 보입니다. 여기에는 인라인 [webpack 로더 요청](https://webpack.github.io/docs/loaders.html)이 사용됩니다. 위 코드에 대해서 간단한 설명을 하겠습니다.
43 |
44 | - `!!`는 "글로벌 설정에서 모든 로더를 사용하지 못하게 함"을 의미합니다.
45 | - `vue?inject!`는 `vue` 로더를 사용하고 `?inject` 쿼리를 전달한다는 것을 의미합니다. 이것은 `vue-loader`에게 의존성 주입 모드로 컴퍼넌트를 컴파일하도록 알려줍니다.
46 |
47 | 반환된 `ExampleInjector`는 `example.vue` 모듈의 인스턴스를 생성하기 위해 호출 될 수 있는 팩토리 함수입니다.
48 |
49 | ``` js
50 | const ExampleWithMocks = ExampleInjector({
51 | // 가짜로 만듭니다
52 | '../service': {
53 | msg: 'Hello from a mocked service!'
54 | }
55 | })
56 | ```
57 |
58 | 마지막으로 우리는 컴포넌트를 평상시에 테스트 할 수 있습니다.
59 |
60 | ``` js
61 | it('should render', () => {
62 | const vm = new Vue({
63 | template: '
',
64 | components: {
65 | 'test': ExampleWithMocks
66 | }
67 | }).$mount()
68 | expect(vm.$el.querySelector('.msg').textContent).toBe('Hello from a mocked service!')
69 | })
70 | ```
71 |
--------------------------------------------------------------------------------
/docs/pt_BR/README.md:
--------------------------------------------------------------------------------
1 | # Introdução
2 |
3 | ### O que é `vue-loader`?
4 |
5 | `vue-loader` é um carregador para Webpack capaz de transformar componentes Vue, como o exemplo abaixo, em um módulo JavaScript sem formatação:
6 |
7 | 
8 |
9 | O `vue-loader` fornece muitos recursos interessantes:
10 |
11 | - ES2015 habilitado por padrão;
12 | - Permite usar outros carregadores Webpack para cada parte de um componente Vue, por exemplo SASS para `
17 | ```
18 |
19 | Por baixo do capô, o conteúdo de texto dentro da tag `
79 | ```
80 |
81 | Contudo, observe que isso faz com que seu componente Vue se torne especifico para Webpack e não compatível com Browserify e [vueify](https://github.com/vuejs/vueify). **Se você pretende enviar seu componente Vue como um componente reutilizável para terceiros, evite usar está sintaxe**.
82 |
--------------------------------------------------------------------------------
/docs/pt_BR/features/es2015.md:
--------------------------------------------------------------------------------
1 | # ES2015
2 |
3 | Quando `vue-loader` detecta a presença de `babel-loader` ou `buble-loader` no mesmo projeto, ele irá usá-los para processar pedaços `
23 | ```
24 |
25 | Estamos usando a abreviação de objeto literal do ES2015 para definir componentes filho. `{ ComponentA }` é simplesmente uma abreviatura para `{ ComponentA: ComponentA }`. Vue irá automaticamente converter a chave para `component-a`, então você pode usar o componente importado no template como ``.
26 |
27 | ### ES2015 em Templates
28 |
29 | `` em arquivos `*.vue` são compilados em funções de renderização do JavaScript e então processados por uma compilação personalizada de [Buble](https://buble.surge.sh/guide/) para suportar características ES2015. Isso permite que você use recursos como [propriedade de abreviatura do objeto](https://buble.surge.sh/guide/#object-shorthand-methods-and-properties-transforms-concisemethodproperty-) e [propriedades computadas](https://buble.surge.sh/guide/#computed-properties-transforms-computedproperty-):
30 |
31 | ```html
32 |
33 | ```
34 |
35 | Pode ser simplificado para:
36 |
37 | ```html
38 |
39 | ```
40 |
41 | **vue@^2.1.0 somente:** você pode usar desestruturação de parâmetro com `v-for` ou escopo de slots:
42 |
43 | ```html
44 |
45 | {{ id }} {{ text }}
46 |
47 | ```
48 |
49 | ```html
50 |
51 |
52 | {{ id }} {{ text }}
53 |
54 |
55 | ```
56 |
57 | Você também pode personalizar os recursos suportados em template usando as [opções de `buble`](../options.md#buble).
58 |
59 | ### Transpilação normal de arquivos `.js`
60 |
61 | Uma vez que `vue-loader` processa apenas arquivos `*.vue`, você precisa informar ao Webpack para processar arquivos `*.js` normais com `babel-loader` ou `buble-loader` em seu arquivo de configuração Webpack. O projeto esqueleto criado com `vue-cli` já faz isso pra você.
62 |
63 | ### Configurando Babel com `.babelrc`
64 |
65 | `babel-loader` respeita [`.babelrc`](https://babeljs.io/docs/usage/babelrc/), portanto essa é a abordagem recomentada para configurar as predefinições e os plugins Babel.
--------------------------------------------------------------------------------
/docs/pt_BR/features/hot-reload.md:
--------------------------------------------------------------------------------
1 | # Hot Reload
2 |
3 | "Hot Reload" \(Recarga Automática\) não é simplesmente recarregar a página quando você editar um arquivo. Com hot reload ativado, quando você edita um arquivo `*.vue`, todas as instâncias desse componente serão trocadas **sem recarregar a página**. Ele ainda preserva o estado atual de sua aplicação e dos componentes trocados. Isto melhora drasticamente a experiência de desenvolvimento quando você está ajustando os modelos ou estilo de seus componentes.
4 |
5 | 
6 |
7 | Quando o esqueleto do projeto é criado com `vue-cli`, Hot Reload é ativado e proto para o uso.
--------------------------------------------------------------------------------
/docs/pt_BR/features/postcss.md:
--------------------------------------------------------------------------------
1 | # PostCSS
2 |
3 | Qualquer saída CSS processada por `vue-loader` é canalizada através de [PostCSS](https://github.com/postcss/postcss) para escrever o escopo CSS. Você também pode adicionar plugins PostCSS personalizado ao processador, por exemplo [autoprefixer](https://github.com/postcss/autoprefixer) ou [CSSNext](http://cssnext.io/).
4 |
5 | ## Usando um Arquivo de Configuração
6 |
7 | A partir da versão 11.0, `vue-loader` suporta o carregamento automático dos mesmo arquivos de configuração do PostCss suportados por [`postcss-loader`](https://github.com/postcss/postcss-loader#usage):
8 |
9 | - `postcss.config.js`
10 | - `.postcssrc`
11 | - Opção `postcss` em `package.json`
12 |
13 | O uso de um arquivo de configuração permite que você compartilhe a mesma configuração entre seus arquivos CSS normais processados por `postcss-loader` e os arquivos CSS dentro de arquivos `*.vue`, isto é o recomendado.
14 |
15 | ## Opções em Linha
16 |
17 | Como alternativa, você pode especificar configurações postcss especificamente para arquivos `*.vue` usando a opção `postcss` para `vue-loader`.
18 |
19 | Exemplo de uso no Webpack 1.x:
20 |
21 | ```js
22 | // webpack.config.js
23 | module.exports = {
24 | // outras configurações...
25 | vue: {
26 | // use plugins personalizado de postcss
27 | postcss: [require('postcss-cssnext')()]
28 | }
29 | }
30 | ```
31 |
32 | Para Webpack 2.x:
33 |
34 | ```js
35 | // webpack.config.js
36 | module.exports = {
37 | // outras opções...
38 | module: {
39 | // module.rules é o mesmo que module.loaders em 1.x
40 | rules: [
41 | {
42 | test: /\.vue$/,
43 | loader: 'vue-loader',
44 | // opções vue-loader options vai aqui
45 | options: {
46 | // ...
47 | postcss: [require('postcss-cssnext')()]
48 | }
49 | }
50 | ]
51 | }
52 | }
53 | ```
54 |
55 | Além de fornecer uma coleção de plugins, a opção de `postcss` também aceita:
56 |
57 | - Uma função que retorna uma coleção de plugins:
58 |
59 | - Um objeto que contém opções para ser passado para o processador PostCSS. Isto é útil quando você está usando projetos com PostCSS que depende de analisadores/stringifiers personalizados:
60 |
61 | ```js
62 | postcss: {
63 | plugins: [...], // Lista de Plugins
64 | options: {
65 | parser: sugarss // Use o analisador sugarss
66 | }
67 | }
68 | ```
--------------------------------------------------------------------------------
/docs/pt_BR/features/scoped-css.md:
--------------------------------------------------------------------------------
1 | # CSS com Escopo
2 |
3 | Quando uma tag `
11 |
12 |
13 |
28 |
29 | ```
30 |
31 | #### Observações
32 |
33 | 1. Você pode incluir ambos os estilos com escopo e sem escopo no mesmo componente:
34 |
35 | ```html
36 |
39 |
40 |
43 | ```
44 |
45 | 2. Um nó raiz do componente filho irá ser afetado por ambos os CSS com escopo dos parentes e o CSS com escopo dos filhos.
46 |
47 | 3. Templates parciais não são afetados por estilo com escopo.
48 |
49 | 4. **Os estilos com escopo não eliminam a necessidade de classes**. Devido a forma como navegadores processam vários seletores CSS, `p { color: red }` irá ser muitas vezes mais lento quando com escopo \(exemplo: quando combinado com um seletor de atributo\). Se você usa classes ou ids ao invés, como em `.example { color: red }`, então você elimina praticamente esse desempenho atingido. [Aqui está um playground](http://stevesouders.com/efws/css-selectors/csscreate.php) onde você pode testar as diferenças você mesmo.
50 |
51 | 5. **Tenha cuidado com seletores descendentes em componentes recursivos!** Para uma regra CSS com o seletor `.a .b`, se o elemento que coincide com `.a` contém um componente filho recursivo, então todos os `.b` nesse componente filho serão correspondidos pela regra.
--------------------------------------------------------------------------------
/docs/pt_BR/start/setup.md:
--------------------------------------------------------------------------------
1 | # Configurando um Projeto
2 |
3 | ### Usando `vue-cli`
4 |
5 | Recomenda-se o gerador de esqueleto do projeto usando `vue-loader` com `vue-cli`:
6 |
7 | ``` bash
8 | npm install -g vue-cli
9 | vue init webpack-simple ola-vue
10 | cd ola-vue
11 | npm install
12 | npm run dev # pronto para começar!
13 | ```
--------------------------------------------------------------------------------
/docs/pt_BR/workflow/linting.md:
--------------------------------------------------------------------------------
1 | # Análise estática do código \(Linting\)
2 |
3 | Você pode ter se perguntado como você analisa seu código dentro dos seus arquivos `*.vue`, uma vez que eles não são JavaScript. Vamos supor que você está usando [ESLint](http://eslint.org/) \(se você não está, deveria\).
4 |
5 | Você também precisará do [eslint-plugin-html](https://github.com/BenoitZugmeyer/eslint-plugin-html) que suporte de extração e análise estática \(linting\) do JavasScript dentro dos arquivos `*.vue`.
6 |
7 | Certifique-se de incluir o plugin dentro de suas configurações ESLint:
8 |
9 | ```json
10 | "plugins": [
11 | "html"
12 | ]
13 | ```
14 |
15 | Em seguida, a partir da linha de comando:
16 |
17 | ```bash
18 | eslint --ext js,vue MeuComponente.vue
19 | ```
20 |
21 | Outra opção é usar [eslint-loader](https://github.com/MoOx/eslint-loader) para que seus arquivos `*.vue` sejam automaticamente analisados ao serem salvo durante o desenvolvimento:
22 |
23 | ```bash
24 | npm install eslint eslint-loader --save-dev
25 | ```
26 |
27 | ```js
28 | // webpack.config.js
29 | module.exports = {
30 | // ... outras opções
31 | module: {
32 | loaders: [
33 | {
34 | test: /.vue$/,
35 | loader: 'vue!eslint'
36 | }
37 | ]
38 | }
39 | }
40 | ```
41 |
42 | Lembre-se que a sequência dos carregadores Webpack são aplicados da **direita para esquerda**. Certifique-se de aplicar `eslint` antes de `vue`, de modo que estamos analisando o código fonte pré-compilado.
43 |
44 | Uma coisa que precisamos considerar é o uso de componente `*.vue` de terceiros enviados em pacote NPM. Neste caso, usaremos `vue-loader` para processar os componentes de terceiros, mas não queremos aplicar a análise de código estático \(linting\). Para isso nós podemos separar o linting em [preLoaders](https://webpack.github.io/docs/loaders.html#loader-order) do Webpack.
45 |
46 | ```js
47 | // webpack.config.js
48 | module.exports = {
49 | // ... outras opções
50 | module: {
51 | // lint apenas em arquivos *.vue locais
52 | preLoaders: [
53 | {
54 | test: /.vue$/,
55 | loader: 'eslint',
56 | exclude: /node_modules/
57 | }
58 | ],
59 | // mas usa vue-loader para todos arquivos *.vue
60 | loaders: [
61 | {
62 | test: /.vue$/,
63 | loader: 'vue'
64 | }
65 | ]
66 | }
67 | }
68 | ```
69 |
70 | Para Webpack 2.x:
71 |
72 | ```js
73 | // webpack.config.js
74 | module.exports = {
75 | // ... outras opções
76 | module: {
77 | rules: [
78 | // lint apenas em arquivos *.vue locais
79 | {
80 | enforce: 'pre',
81 | test: /.vue$/,
82 | loader: 'eslint-loader',
83 | exclude: /node_modules/
84 | },
85 | // mas usa vue-loader para todos arquivos *.vue
86 | {
87 | test: /.vue$/,
88 | loader: 'vue-loader'
89 | }
90 | ]
91 | }
92 | }
93 | ```
--------------------------------------------------------------------------------
/docs/pt_BR/workflow/production.md:
--------------------------------------------------------------------------------
1 | # Construir produção
2 |
3 | Há duas coisas a fazer ao construir nosso pacote para produção:
4 |
5 | 1. Minificar o código de nossa aplicação;
6 | 2. Use a [configuração descrita no guia Vue.js](https://vuejs.org/guide/deployment.html) para remover todos os avisos de código-fonte Vue.js;
7 |
8 | Aqui está um exemplo de configuração:
9 |
10 | ```js
11 | // webpack.config.js
12 | module.exports = {
13 | // ...outras opções
14 | plugins: [
15 | // liga em curto-circuito todo código de aviso Vue.js
16 | new webpack.DefinePlugin({
17 | 'process.env': {
18 | NODE_ENV: '"production"'
19 | }
20 | }),
21 | // minifica com eliminação de código morto
22 | new webpack.optimize.UglifyJsPlugin({
23 | compress: {
24 | warnings: false
25 | }
26 | }),
27 | // Webpack 1 apenas - otimiza ids de módulo por contagem de ocorrências
28 | new webpack.optimize.OccurrenceOrderPlugin()
29 | ]
30 | }
31 | ```
32 |
33 | Obviamente não queremos usar estás configurações durante o desenvolvimento, então há várias maneiras de abordar isso:
34 |
35 | 1. Crie dinamicamente o objeto de configuração com base em uma variável de ambiente.
36 |
37 | 2. Ou use dois arquivos de configuração do Webpack separados, um para o desenvolvimento e outro para produção. E talvez compartilhe algumas opções comuns entre eles em um terceiro arquivo, como mostrado em [vue-hackernews-2.0](https://github.com/vuejs/vue-hackernews-2.0).
38 |
39 | Isto é com você, desde que o objetivo seja atingido.
40 |
--------------------------------------------------------------------------------
/docs/pt_BR/workflow/testing-with-mocks.md:
--------------------------------------------------------------------------------
1 | # Testes com Mocks
2 |
3 | Em uma aplicação do mundo real, nossos componentes provavelmente tem uma dependência externa. Ao escrever testes de unidades para componentes, seria ideal se pudéssemos simular \(mock\) essas dependências externas de modo que nossos testes dependam apenas do comportamento do componente que está sendo testado.
4 |
5 | `vue-loader` fornece um recurso que permite você injetar dependências arbitrária para um componente `*.vue`, usando o [inject-loader](https://github.com/plasticine/inject-loader). A ideia geral é que, em vez de importar diretamente o módulo componente, nós usaremos `inject-loader` para criar uma função "fábrica de módulos" para este módulo. Quando está função é chamada com um objeto de mocks, ele retorna uma instância do módulo com os mocks injetados.
6 |
7 | Suponha que temos um componente como este:
8 |
9 | ```html
10 |
11 |
12 |
{{ msg }}
13 |
14 |
15 |
27 | ```
28 |
29 | Veja como importá-lo com simulações:
30 |
31 | > Nota: inject-loader@3.x está atualmente instável.
32 |
33 | ```bash
34 | npm install inject-loader@^2.0.0 --save-dev
35 | ```
36 |
37 | ```js
38 | // exemplo.spec.js
39 | const ExemploInjecao = require('!!vue?inject!./exemplo.vue')
40 | ```
41 |
42 | Observe que ele requer uma sequência de caracteres - nós estamos usando algumas [requisições de carregador webpack](https://webpack.github.io/docs/loaders.html) em linha aqui. Uma explicação rápida:
43 |
44 | - `!!` no início significa "desative todos os carregadores da configuração global";
45 | - `vue?inject!` significa "use o carregador de `vue`, e passe o `?inject` na consulta". Isso informa ao `vue-loader` para compilar o componente no modo injeção de dependência.
46 |
47 | O retorno de `ExemploInjecao` é uma função de fábrica que pode ser chamada para criar instâncias do módulo `exemplo.vue`.
48 |
49 | ```js
50 | const ExemploComMocks = ExemploInjecao({
51 | // simulação de serviço
52 | '../servico': {
53 | msg: 'Olá de uma simulação de serviço!'
54 | }
55 | })
56 | ```
57 |
58 | Finalmente, podemos testar o componente como de costume:
59 |
60 | ```js
61 | it('Deve renderizar', () => {
62 | const vm = new Vue({
63 | template: '
',
64 | components: {
65 | 'test': ExemploComMocks
66 | }
67 | }).$mount()
68 | expect(vm.$el.querySelector('.msg').textContent).toBe('Olá de uma simulação de serviço!')
69 | })
70 | ```
--------------------------------------------------------------------------------
/docs/ru/README.md:
--------------------------------------------------------------------------------
1 | # Введение
2 |
3 | ### Что такое `vue-loader`?
4 |
5 | `vue-loader` – это загрузчик для Webpack, который преобразует Vue компоненты, написанные в следующем формате в обычные JavaScript модули:
6 |
7 | 
8 |
9 | `vue-loader` предлагает множество полезных возможностей:
10 |
11 | - Поддержка ES2015 по умолчанию;
12 | - Позволяет использовать разные загрузчики Webpack для разных частей Vue компонента, например, SASS для `
17 | ```
18 |
19 | В недрах, текстовое содержимое тега `
79 | ```
80 |
81 | Обратите внимание, это сделает ваш компонент Vue зависимым от Webpack и несовместимым с Browserify и [vueify](https://github.com/vuejs/vueify). **Если вы планируете распространять ваш компонент Vue, избегайте использования этого синтаксиса.**
82 |
--------------------------------------------------------------------------------
/docs/ru/features/es2015.md:
--------------------------------------------------------------------------------
1 | # ES2015
2 |
3 | Когда `vue-loader` обнаруживает наличие `babel-loader` или `buble-loader` в том же проекте, он будет использовать их для обработки секций `
23 | ```
24 |
25 | В нём была использована краткая запись свойства объекта, доступная в ES2015 для определения дочерних компонентов. `{ ComponentA }` это попросту сокращение от `{ ComponentA: ComponentA }`. Vue автометически преобразует ключ в `component-a`, так что вы можете использовать импортированный компонент в шаблоне как ``.
26 |
27 | ### ES2015 в шаблонах
28 |
29 | Секция `` в `*.vue` файлах компилируется в `render`-функцию на JavaScript и потом обрабатывается собственной сборкой [Buble](https://buble.surge.sh/guide/) для поддержки ES2015. Это позволяет вам использовать такие возможности как [краткую запись свойства объекта](https://buble.surge.sh/guide/#object-shorthand-methods-and-properties-transforms-concisemethodproperty-) и [вычисляемые свойства](https://buble.surge.sh/guide/#computed-properties-transforms-computedproperty-):
30 |
31 | ``` html
32 |
33 | ```
34 |
35 | можно упростить до:
36 |
37 | ``` html
38 |
39 | ```
40 |
41 | **только для версий vue@^2.1.0:** Вы можете использовать деструктуризацию параметров в `v-for` или слотах с ограниченной областью видимости:
42 |
43 | ``` html
44 |
45 | {{ id }} {{ text }}
46 |
47 | ```
48 |
49 | ``` html
50 |
51 |
52 | {{ id }} {{ text }}
53 |
54 |
55 | ```
56 |
57 | Вы также можете настроить доступные возможности в шаблонах с помощью [опции `buble`](../options.md#buble).
58 |
59 | ### Транспиляция обычных `.js` файлов
60 |
61 | Так как `vue-loader` обрабатывает только `*.vue` файлы, вам нужно настроить в файле конфигурации Webpack чтобы обычные `*.js` файлы обрабатывались с помощью `babel-loader` или `buble-loader`. Проект созданный с помощью `vue-cli` уже настроен таким образом.
62 |
63 | ### Настройка Babel с помощью `.babelrc`
64 |
65 | `babel-loader` предпочитает [`.babelrc`](https://babeljs.io/docs/usage/babelrc/), поэтому рекомендуем использовать именно его для настройки пресетов и плагинов Babel.
66 |
--------------------------------------------------------------------------------
/docs/ru/features/hot-reload.md:
--------------------------------------------------------------------------------
1 | # Горячая замена
2 |
3 | "Горячая замена" это не просто обновление страницы, когда вы отредактируете файл. При использовании горячей замены, когда вы отредактируете `*.vue` файл, все экземпляры этого компонента будут заменены **без перезагрузки страницы**. При этом даже будет сохранено текущее состояние вашего приложения и заменяемых компонентов! Это значительно улучшает процесс разработки, особенно когда вы занимаетесь тонкой настройкой шаблонов или стилей ваших компонентов.
4 |
5 | 
6 |
7 | При создании проекта с помощью `vue-cli`, горячая замена включена по умолчанию.
8 |
--------------------------------------------------------------------------------
/docs/ru/features/postcss.md:
--------------------------------------------------------------------------------
1 | # PostCSS
2 |
3 | Любой CSS проходящий через `vue-loader` обрабатывается [PostCSS](https://github.com/postcss/postcss) для реализации функциональности scoped CSS. Вы также можете добавить другие плагины PostCSS к процессу обработки. Например, [autoprefixer](https://github.com/postcss/autoprefixer) или [CSSNext](http://cssnext.io/).
4 |
5 | ## Использование файла конфигурации
6 |
7 | Начиная с версии 11.0 `vue-loader` поддерживает файлы конфигурации PostCSS поддерживаемые с помощью [`postcss-loader`](https://github.com/postcss/postcss-loader#usage):
8 |
9 | - `postcss.config.js`
10 | - `.postcssrc`
11 | - `postcss` поле в `package.json`
12 |
13 | Рекомендуется использовать файл конфигурации, это позволяет использовать один и тот же конфиг для обработки ваших CSS файлов, обрабатываемых `postcss-loader` и CSS внутри `*.vue` файлов.
14 |
15 | ## Указание настроек в опциях vue-loader
16 |
17 | В качестве альтернативы, вы можете указать конфигурацию PostCSS специально для `*.vue` файлов с помощью опции `postcss` для `vue-loader`.
18 |
19 | Пример использования с Webpack 1.x:
20 |
21 | ``` js
22 | // webpack.config.js
23 | module.exports = {
24 | // другие настройки...
25 | vue: {
26 | // использование плагинов postcss
27 | postcss: [require('postcss-cssnext')()]
28 | }
29 | }
30 | ```
31 |
32 | Для Webpack 2.x:
33 |
34 | ``` js
35 | // webpack.config.js
36 | module.exports = {
37 | // другие настройки...
38 | module: {
39 | // module.rules тоже самое, что и module.loaders в 1.x
40 | rules: [
41 | {
42 | test: /\.vue$/,
43 | loader: 'vue-loader',
44 | // настройки vue-loader
45 | options: {
46 | // ...
47 | postcss: [require('postcss-cssnext')()]
48 | }
49 | }
50 | ]
51 | }
52 | }
53 | ```
54 |
55 | В дополнение к возможности использовать массив плагинов, опция `postcss` также принимает:
56 |
57 | - Функцию, возвращающую массив плагинов;
58 |
59 | - Объект, который содержит настройки для передачи в PostCSS. Это пригодится если вы используете проекты с PostCSS которые опираются на пользовательские парсеры/сериализаторы:
60 |
61 | ``` js
62 | postcss: {
63 | plugins: [...], // список плагинов
64 | options: {
65 | parser: sugarss // использование парсера sugarss
66 | }
67 | }
68 | ```
69 |
--------------------------------------------------------------------------------
/docs/ru/features/scoped-css.md:
--------------------------------------------------------------------------------
1 | # Локальный CSS
2 |
3 | Когда у тега `
11 |
12 |
13 |
hi
14 |
15 | ```
16 |
17 | В что-то подобное:
18 |
19 | ``` html
20 |
25 |
26 |
27 |
hi
28 |
29 | ```
30 |
31 | #### Примечания
32 |
33 | 1. Вы можете использовать в компоненте локальные и глобальные стили одновременно:
34 |
35 | ``` html
36 |
39 |
40 |
43 | ```
44 |
45 | 2. Корневой тег компонента потомка будет попадать под область видимости родительского локального CSS и своего локального CSS.
46 |
47 | 3. Partials не затрагиваются локальными стилями.
48 |
49 | 4. **Локальные стили не устраняют необходимость классов**. Из-за того как браузеры рендерят различные CSS-селекторы, `p { color: red }` может быть в разы медленнее при использовании в локальных стилях (например, когда комбинируется с селектором по атрибуту). Если же вы используете классы или ID, такие как `.example { color: red }`, тогда вы практически полностью исключаете ухудшение производительности. [Вот пример](http://stevesouders.com/efws/css-selectors/csscreate.php) где вы можете проверить разницу самостоятельно.
50 |
51 | 5. **Будьте внимательны с селекторами потомков в рекурсивных компонентах!** Для CSS-правила с селектором `.a .b`, если элемент, который соответствует `.a` содержит рекурсивный компонент потомок, тогда все `.b` в этом компоненте потомке будут также соответствовать правилу.
52 |
--------------------------------------------------------------------------------
/docs/ru/start/setup.md:
--------------------------------------------------------------------------------
1 | # Создание проекта
2 |
3 | ### Использование `vue-cli`
4 |
5 | Рекомендуем создавать проекты, использующие `vue-loader`, с помощью `vue-cli`:
6 |
7 | ``` bash
8 | npm install -g vue-cli
9 | vue init webpack-simple hello-vue
10 | cd hello-vue
11 | npm install
12 | npm run dev # можно начинать!
13 | ```
14 |
--------------------------------------------------------------------------------
/docs/ru/workflow/linting.md:
--------------------------------------------------------------------------------
1 | # Статические анализаторы
2 |
3 | Вы, возможно, гадаете, как же прогонять код в `*.vue` файлах через статические анализаторы, поскольку это не JavaScript. Мы предполагаем, что вы используете [ESLint](http://eslint.org/) (если нет, настоятельно рекомендуем!).
4 |
5 | Вам также понадобится [eslint-html-plugin](https://github.com/BenoitZugmeyer/eslint-plugin-html) с поддержкой извлечения и анализа JavaScript в `*.vue` файлах.
6 |
7 | Убедитесь в том, что вы добавили плагин в конфигурацию ESLint:
8 |
9 | ``` json
10 | "plugins": [
11 | "html"
12 | ]
13 | ```
14 |
15 | Затем в командной строке:
16 |
17 | ``` bash
18 | eslint --ext js,vue MyComponent.vue
19 | ```
20 |
21 | Другой вариант – использовать [eslint-loader](https://github.com/MoOx/eslint-loader), который будет автоматически анализировать `*.vue` файлы после сохранения во время разработки:
22 |
23 | ``` bash
24 | npm install eslint eslint-loader --save-dev
25 | ```
26 |
27 | ``` js
28 | // webpack.config.js
29 | module.exports = {
30 | // ... прочие опции
31 | module: {
32 | loaders: [
33 | {
34 | test: /.vue$/,
35 | loader: 'vue!eslint'
36 | }
37 | ]
38 | }
39 | }
40 | ```
41 |
42 | Обратите внимание, что загрузчики Webpack применяются **справа-налево**. Убедитесь, что `eslint` прописан перед `vue`, чтобы код сначала проходил через анализатор, а затем компилировался.
43 |
44 | Стоит упомянуть об использовании сторонних `*.vue` компонентов, поставляемых в NPM пакетах. В таком случае нам нужно воспользоваться `vue-loader`? чтобы подключить сторонние компоненты, но не анализировать их. Мы можем вынести анализ в [предзагрузчики](https://webpack.github.io/docs/loaders.html#loader-order) Webpack:
45 |
46 | ``` js
47 | // webpack.config.js
48 | module.exports = {
49 | // ... прочие опции
50 | module: {
51 | // анализировать только локальные *.vue файлы
52 | preLoaders: [
53 | {
54 | test: /.vue$/,
55 | loader: 'eslint',
56 | exclude: /node_modules/
57 | }
58 | ],
59 | // но использовать vue-loader для всех *.vue файлов
60 | loaders: [
61 | {
62 | test: /.vue$/,
63 | loader: 'vue'
64 | }
65 | ]
66 | }
67 | }
68 | ```
69 |
70 | Для Webpack 2.x:
71 |
72 | ``` js
73 | // webpack.config.js
74 | module.exports = {
75 | // ... прочие опции
76 | module: {
77 | rules: [
78 | // анализировать только локальные *.vue файлы
79 | {
80 | enforce: 'pre',
81 | test: /.vue$/,
82 | loader: 'eslint-loader',
83 | exclude: /node_modules/
84 | },
85 | // но использовать vue-loader для всех *.vue файлов
86 | {
87 | test: /.vue$/,
88 | loader: 'vue-loader'
89 | }
90 | ]
91 | }
92 | }
93 | ```
94 |
--------------------------------------------------------------------------------
/docs/ru/workflow/production.md:
--------------------------------------------------------------------------------
1 | # Сборка продакшна
2 |
3 | Когда мы собираем финальную версию приложения, мы делаем две вещи:
4 |
5 | 1. Минифицируем код нашего приложения;
6 | 2. Используем [описанные в руководстве по Vue.js настройки](https://ru.vuejs.org/v2/guide/deployment.html), чтобы устранить все возможные проблемы в коде
7 |
8 | Вот пример конфигурации:
9 |
10 | ``` js
11 | // webpack.config.js
12 | module.exports = {
13 | // ... прочие опции
14 | plugins: [
15 | // разбираемся со всеми предупреждениями в нашем Vue.js коде
16 | new webpack.DefinePlugin({
17 | 'process.env': {
18 | NODE_ENV: '"production"'
19 | }
20 | }),
21 | // минифицируем, устраняя весь ненужный код
22 | new webpack.optimize.UglifyJsPlugin({
23 | compress: {
24 | warnings: false
25 | }
26 | }),
27 | // только для Webpack 1 – оптимизируем идентификаторы модулей по числу использований
28 | new webpack.optimize.OccurrenceOrderPlugin()
29 | ]
30 | }
31 | ```
32 |
33 | Очевидно, нам ни к чему использовать эту конфигурацию во время разработки, для этого есть несколько вариантов:
34 |
35 | 1. Динамически собирать объект конфигурации на основе переменных окружения;
36 |
37 | 2. Или использовать два отдельных конфигурационных файла Webpack, один для разработки, и один для продакшна. И возможно хранить некоторые их общие опции в третьем файле, как показано в [vue-hackernews-2.0](https://github.com/vuejs/vue-hackernews-2.0).
38 |
39 | Не имеет значения, как вы будете это делать, если это решит задачу.
40 |
--------------------------------------------------------------------------------
/docs/ru/workflow/testing-with-mocks.md:
--------------------------------------------------------------------------------
1 | # Тестирование с моками
2 |
3 | В настоящих приложениях наши компоненты скорее всего будут иметь внешние зависимости. Было бы прекрасно, если бы мы могли полностью контролировать эти зависимости в наших тестах, чтобы они опирались только на поведение тестируемого компонента.
4 |
5 | Для этого в модульных тестах используется понятие "мок" ("mock") – это объект, за вызовами методов которого мы можем следить и даже управлять их результатами. Чтобы не тестировать и компонент, и его зависимость в связке, нам достаточно внедрить вместо зависимости созданный мок-объект.
6 |
7 | `vue-loader` предоставляет возможность внедрять произвольные зависимости в `*.vue` компоненты, используя [inject-loader](https://github.com/plasticine/inject-loader). Основная идея состоит в том, что вместо прямой подгрузки модуля компонента мы используем `inject-loader`, чтобы создать "фабричную функцию" для этого модуля. Когда мы вызовем эту функцию с мок-объектом, она вернет нам экземпляр модуля с внедренными мок-объектами.
8 |
9 | Допустим, у нас есть следующий компонент:
10 |
11 | ``` html
12 |
13 |
14 |
{{ msg }}
15 |
16 |
17 |
29 | ```
30 |
31 | Вот как получить его с мок-объектами:
32 |
33 | > Заметка: inject-loader@3.x еще не в стабильной версии
34 |
35 | ``` bash
36 | npm install inject-loader@^2.0.0 --save-dev
37 | ```
38 |
39 | ``` js
40 | // example.spec.js
41 | const ExampleInjector = require('!!vue?inject!./example.vue')
42 | ```
43 |
44 | Обратите внимание на эту безумную строку импорта – мы используем [запросы к webpack загрузчику](https://webpack.github.io/docs/loaders.html). Краткое пояснение:
45 |
46 | - `!!` в начале строки означает "отключи все загрузчики из глобальной конфигурации"
47 | - `vue?inject!` значит "используй `vue` загрузчик и передай запрос `?inject`". Это заставляет `vue-loader` скомпилировать компонент в режиме внедрения зависимостей.
48 |
49 | Полученный `ExampleInjector` – это фабричная функция, которую можно вызвать, чтобы создать экземпляр модуля `example.vue`:
50 |
51 | ``` js
52 | const ExampleWithMocks = ExampleInjector({
53 | // mock it
54 | '../service': {
55 | msg: 'Привет от мок-сервиса!'
56 | }
57 | })
58 | ```
59 |
60 | Наконец, мы можем тестировать компонент как обычно:
61 |
62 | ``` js
63 | it('should render', () => {
64 | const vm = new Vue({
65 | template: '