├── .gitignore
├── README.md
├── circle.yml
├── deploy-docs.sh
├── docs
├── README.md
├── SUMMARY.md
├── backend.md
├── commands.md
├── e2e.md
├── env.md
├── linter.md
├── pre-processors.md
├── prerender.md
├── proxy.md
├── static.md
├── structure.md
└── unit.md
├── meta.js
├── package.json
├── template
├── .babelrc
├── .editorconfig
├── .eslintignore
├── .eslintrc.js
├── .gitignore
├── .postcssrc.js
├── README.md
├── build
│ ├── build.js
│ ├── check-versions.js
│ ├── dev-client.js
│ ├── dev-server.js
│ ├── utils.js
│ ├── vue-loader.conf.js
│ ├── webpack.base.conf.js
│ ├── webpack.dev.conf.js
│ ├── webpack.prod.conf.js
│ └── webpack.test.conf.js
├── config
│ ├── dev.env.js
│ ├── index.js
│ ├── prod.env.js
│ └── test.env.js
├── index.html
├── package.json
├── package.swan.json
├── project.config.json
├── project.swan.json
├── src
│ ├── App.vue
│ ├── app.json
│ ├── components
│ │ └── card.vue
│ ├── main.js
│ ├── pages
│ │ ├── counter
│ │ │ ├── index.vue
│ │ │ ├── main.js
│ │ │ └── store.js
│ │ ├── index
│ │ │ ├── index.vue
│ │ │ └── main.js
│ │ └── logs
│ │ │ ├── index.vue
│ │ │ ├── main.js
│ │ │ └── main.json
│ └── utils
│ │ └── index.js
├── static
│ ├── .gitkeep
│ ├── images
│ │ └── user.png
│ └── tabs
│ │ ├── home-active.png
│ │ ├── home.png
│ │ ├── orders-active.png
│ │ └── orders.png
└── test
│ ├── e2e
│ ├── custom-assertions
│ │ └── elementCount.js
│ ├── nightwatch.conf.js
│ ├── runner.js
│ └── specs
│ │ └── test.js
│ └── unit
│ ├── .eslintrc
│ ├── index.js
│ ├── karma.conf.js
│ └── specs
│ └── Hello.spec.js
└── test.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | .DS_Store
3 | docs/_book
4 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # mpvue-quickstart
2 |
3 | > fork 自 [vuejs-templates/webpack](https://github.com/vuejs-templates/webpack)修改而来。
4 |
5 | ## 基本用法
6 | ``` bash
7 | $ npm install -g vue-cli
8 | $ vue init mpvue/mpvue-quickstart my-project
9 | $ cd my-project
10 | $ npm install
11 | $ npm run dev
12 | ```
13 |
14 | 更多详细文档请查阅 [quickstart](http://mpvue.com/mpvue/quickstart/)。
15 |
16 | bug 或者交流建议等请反馈到 [mpvue/issues](https://github.com/Meituan-Dianping/mpvue/issues)。
17 |
--------------------------------------------------------------------------------
/circle.yml:
--------------------------------------------------------------------------------
1 | machine:
2 | node:
3 | version: stable
4 |
5 | dependencies:
6 | pre:
7 | - sudo sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list'
8 | - sudo apt-get update
9 | - sudo apt-get install google-chrome-stable
10 |
11 | test:
12 | override:
13 | - bash test.sh
14 |
--------------------------------------------------------------------------------
/deploy-docs.sh:
--------------------------------------------------------------------------------
1 | cd docs
2 | rm -rf _book
3 | gitbook build
4 | cd _book
5 | git init
6 | git add -A
7 | git commit -m 'update book'
8 | git push -f git@github.com:vuejs-templates/webpack.git master:gh-pages
9 |
--------------------------------------------------------------------------------
/docs/README.md:
--------------------------------------------------------------------------------
1 | # Introduction
2 |
3 | This boilerplate is targeted towards large, serious projects and assumes you are somewhat familiar with Webpack and `vue-loader`. Make sure to also read [`vue-loader`'s documentation](http://vuejs.github.io/vue-loader/index.html) for common workflow recipes.
4 |
5 | If you just want to try out `vue-loader` or whip out a quick prototype, use the [webpack-simple](https://github.com/vuejs-templates/webpack-simple) template instead.
6 |
7 | ## Quickstart
8 |
9 | To use this template, scaffold a project with [vue-cli](https://github.com/vuejs/vue-cli). **It is recommended to use npm 3+ for a more efficient dependency tree.**
10 |
11 | ``` bash
12 | $ npm install -g vue-cli
13 | $ vue init webpack my-project
14 | $ cd my-project
15 | $ npm install
16 | $ npm run dev
17 | ```
18 |
--------------------------------------------------------------------------------
/docs/SUMMARY.md:
--------------------------------------------------------------------------------
1 | # Summary
2 |
3 | - [Project Structure](structure.md)
4 | - [Build Commands](commands.md)
5 | - [Linter Configuration](linter.md)
6 | - [Pre-Processors](pre-processors.md)
7 | - [Handling Static Assets](static.md)
8 | - [Environment Variables](env.md)
9 | - [Integrate with Backend Framework](backend.md)
10 | - [API Proxying During Development](proxy.md)
11 | - [Unit Testing](unit.md)
12 | - [End-to-end Testing](e2e.md)
13 | - [Prerendering for SEO](prerender.md)
14 |
--------------------------------------------------------------------------------
/docs/backend.md:
--------------------------------------------------------------------------------
1 | # Integrating with Backend Framework
2 |
3 | If you are building a purely-static app (one that is deployed separately from the backend API), then you probably don't even need to edit `config/index.js`. However, if you want to integrate this template with an existing backend framework, e.g. Rails/Django/Laravel, which comes with their own project structures, you can edit `config/index.js` to directly generate front-end assets into your backend project.
4 |
5 | Let's take a look at the default `config/index.js`:
6 |
7 | ``` js
8 | // config/index.js
9 | var path = require('path')
10 |
11 | module.exports = {
12 | build: {
13 | index: path.resolve(__dirname, 'dist/index.html'),
14 | assetsRoot: path.resolve(__dirname, 'dist'),
15 | assetsSubDirectory: 'static',
16 | assetsPublicPath: '/',
17 | productionSourceMap: true
18 | },
19 | dev: {
20 | port: 8080,
21 | proxyTable: {}
22 | }
23 | }
24 | ```
25 |
26 | Inside the `build` section, we have the following options:
27 |
28 | ### `build.index`
29 |
30 | > Must be an absolute path on your local file system.
31 |
32 | This is where the `index.html` (with injected asset URLs) will be generated.
33 |
34 | If you are using this template with a backend-framework, you can edit `index.html` accordingly and point this path to a view file rendered by your backend app, e.g. `app/views/layouts/application.html.erb` for a Rails app, or `resources/views/index.blade.php` for a Laravel app.
35 |
36 | ### `build.assetsRoot`
37 |
38 | > Must be an absolute path on your local file system.
39 |
40 | This should point to the root directory that contains all the static assets for your app. For example, `public/` for both Rails/Laravel.
41 |
42 | ### `build.assetsSubDirectory`
43 |
44 | Nest webpack-generated assets under this directory in `build.assetsRoot`, so that they are not mixed with other files you may have in `build.assetsRoot`. For example, if `build.assetsRoot` is `/path/to/dist`, and `build.assetsSubDirectory` is `static`, then all Webpack assets will be generated in `path/to/dist/static`.
45 |
46 | This directory will be cleaned before each build, so it should only contain assets generated by the build.
47 |
48 | Files inside `static/` will be copied into this directory as-is during build. This means if you change this prefix, all your absolute URLs referencing files in `static/` will also need to be changed. See [Handling Static Assets](static.md) for more details.
49 |
50 | ### `build.assetsPublicPath`
51 |
52 | This should be the URL path where your `build.assetsRoot` will be served from over HTTP. In most cases, this will be root (`/`). Only change this if your backend framework serves static assets with a path prefix. Internally, this is passed to Webpack as `output.publicPath`.
53 |
54 | ### `build.productionSourceMap`
55 |
56 | Whether to generate source maps for production build.
57 |
58 | ### `dev.port`
59 |
60 | Specify the port for the dev server to listen to.
61 |
62 | ### `dev.proxyTable`
63 |
64 | Define proxy rules for the dev server. See [API Proxying During Development](proxy.md) for more details.
65 |
--------------------------------------------------------------------------------
/docs/commands.md:
--------------------------------------------------------------------------------
1 | # Build Commands
2 |
3 | All build commands are executed via [NPM Scripts](https://docs.npmjs.com/misc/scripts).
4 |
5 | ### `npm run dev`
6 |
7 | > Starts a Node.js local development server. See [API Proxying During Development](proxy.md) for more details.
8 |
9 | - Webpack + `vue-loader` for single file Vue components.
10 | - State preserving hot-reload
11 | - State preserving compilation error overlay
12 | - Lint-on-save with ESLint
13 | - Source maps
14 |
15 | ### `npm run build`
16 |
17 | > Build assets for production. See [Integrating with Backend Framework](backend.md) for more details.
18 |
19 | - JavaScript minified with [UglifyJS](https://github.com/mishoo/UglifyJS2).
20 | - HTML minified with [html-minifier](https://github.com/kangax/html-minifier).
21 | - CSS across all components extracted into a single file and minified with [cssnano](https://github.com/ben-eb/cssnano).
22 | - All static assets compiled with version hashes for efficient long-term caching, and a production `index.html` is auto-generated with proper URLs to these generated assets.
23 |
24 | ### `npm run unit`
25 |
26 | > Run unit tests in PhantomJS with [Karma](https://karma-runner.github.io/). See [Unit Testing](unit.md) for more details.
27 |
28 | - Supports ES2015+ in test files.
29 | - Supports all webpack loaders.
30 | - Easy [mock injection](http://vuejs.github.io/vue-loader/en/workflow/testing-with-mocks.html).
31 |
32 | ### `npm run e2e`
33 |
34 | > Run end-to-end tests with [Nightwatch](http://nightwatchjs.org/). See [End-to-end Testing](e2e.md) for more details.
35 |
36 | - Run tests in multiple browsers in parallel.
37 | - Works with one command out of the box:
38 | - Selenium and chromedriver dependencies automatically handled.
39 | - Automatically spawns the Selenium server.
40 |
--------------------------------------------------------------------------------
/docs/e2e.md:
--------------------------------------------------------------------------------
1 | # End-to-end Testing
2 |
3 | This boilerplate uses [Nightwatch.js](http://nightwatchjs.org) for e2e tests. Nightwatch.js is a highly integrated e2e test runner built on top of Selenium. This boilerplate comes with Selenium server and chromedriver binaries pre-configured for you, so you don't have to mess with these yourself.
4 |
5 | Let's take a look at the files in the `test/e2e` directory:
6 |
7 | - `runner.js`
8 |
9 | A Node.js script that starts the dev server, and then launches Nightwatch to run tests against it. This is the script that will run when you run `npm run e2e`.
10 |
11 | - `nightwatch.conf.js`
12 |
13 | Nightwatch configuration file. See [Nightwatch's docs on configuration](http://nightwatchjs.org/guide#settings-file) for more details.
14 |
15 | - `custom-assertions/`
16 |
17 | Custom assertions that can be used in Nightwatch tests. See [Nightwatch's docs on writing custom assertions](http://nightwatchjs.org/guide#writing-custom-assertions) for more details.
18 |
19 | - `specs/`
20 |
21 | Your actual tests! See [Nightwatch's docs on writing tests](http://nightwatchjs.org/guide#writing-tests) and [API reference](http://nightwatchjs.org/api) for more details.
22 |
23 | ### Running Tests in More Browsers
24 |
25 | To configure which browsers to run the tests in, add an entry under "test_settings" in [`test/e2e/nightwatch.conf.js`](https://github.com/vuejs-templates/webpack/blob/master/template/test/e2e/nightwatch.conf.js#L17-L39) , and also the `--env` flag in [`test/e2e/runner.js`](https://github.com/vuejs-templates/webpack/blob/master/template/test/e2e/runner.js#L15). If you wish to configure remote testing on services like SauceLabs, you can either make the Nightwatch config conditional based on environment variables, or use a separate config file altogether. Consult [Nightwatch's docs on Selenium](http://nightwatchjs.org/guide#selenium-settings) for more details.
26 |
--------------------------------------------------------------------------------
/docs/env.md:
--------------------------------------------------------------------------------
1 | # Environment Variables
2 |
3 | Sometimes it is practical to have different config values according to the environment that the application is running in.
4 |
5 | As an example:
6 |
7 | ```js
8 | // config/prod.env.js
9 | module.exports = {
10 | NODE_ENV: '"production"',
11 | DEBUG_MODE: false,
12 | API_KEY: '"..."' // this is shared between all environments
13 | }
14 |
15 | // config/dev.env.js
16 | module.exports = merge(prodEnv, {
17 | NODE_ENV: '"development"',
18 | DEBUG_MODE: true // this overrides the DEBUG_MODE value of prod.env
19 | })
20 |
21 | // config/test.env.js
22 | module.exports = merge(devEnv, {
23 | NODE_ENV: '"testing"'
24 | })
25 | ```
26 |
27 | > **Note:** string variables need to be wrapped into single and double quotes `'"..."'`
28 |
29 | So, the environment variables are:
30 | - Production
31 | - NODE_ENV = 'production',
32 | - DEBUG_MODE = false,
33 | - API_KEY = '...'
34 | - Development
35 | - NODE_ENV = 'development',
36 | - DEBUG_MODE = true,
37 | - API_KEY = '...'
38 | - Testing
39 | - NODE_ENV = 'testing',
40 | - DEBUG_MODE = true,
41 | - API_KEY = '...'
42 |
43 | As we can see, `test.env` inherits the `dev.env` and the `dev.env` inherits the `prod.env`.
44 |
45 | ### Usage
46 |
47 | It is simple to use the environment variables in your code. For example:
48 |
49 | ```js
50 | Vue.config.productionTip = process.env.NODE_ENV === 'production'
51 | ```
52 |
--------------------------------------------------------------------------------
/docs/linter.md:
--------------------------------------------------------------------------------
1 | # Linter Configuration
2 |
3 | This boilerplate uses [ESLint](http://eslint.org/) as the linter, and uses the [Standard](https://github.com/feross/standard/blob/master/RULES.md) preset with some small customizations.
4 |
5 | If you are not happy with the default linting rules, you have several options:
6 |
7 | 1. Overwrite individual rules in `.eslintrc.js`. For example, you can add the following rule to enforce semicolons instead of omitting them:
8 |
9 | ``` js
10 | // .eslintrc.js
11 | "semi": [2, "always"]
12 | ```
13 |
14 | 2. Pick a different ESLint preset when generating the project, for example [eslint-config-airbnb](https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb).
15 |
16 | 3. Pick "none" for ESLint preset when generating the project and define your own rules. See [ESLint documentation](http://eslint.org/docs/rules/) for more details.
17 |
--------------------------------------------------------------------------------
/docs/pre-processors.md:
--------------------------------------------------------------------------------
1 | # Pre-Processors
2 |
3 | This boilerplate has pre-configured CSS extraction for most popular CSS pre-processors including LESS, SASS, Stylus, and PostCSS. To use a pre-processor, all you need to do is installing the appropriate webpack loader for it. For example, to use SASS:
4 |
5 | ``` bash
6 | npm install sass-loader node-sass --save-dev
7 | ```
8 |
9 | Note you also need to install `node-sass` because `sass-loader` depends on it as a peer dependency.
10 |
11 | ### Using Pre-Processors inside Components
12 |
13 | Once installed, you can use the pre-processors inside your `*.vue` components using the `lang` attribute on `
19 | ```
20 |
21 | ### A note on SASS syntax
22 |
23 | - `lang="scss"` corresponds to the CSS-superset syntax (with curly braces and semicolons).
24 | - `lang="sass"` corresponds to the indentation-based syntax.
25 |
26 | ### PostCSS
27 |
28 | Styles in `*.vue` files are piped through PostCSS by default, so you don't need to use a specific loader for it. You can simply add PostCSS plugins you want to use in `build/webpack.base.conf.js` under the `vue` block:
29 |
30 | ``` js
31 | // build/webpack.base.conf.js
32 | module.exports = {
33 | // ...
34 | vue: {
35 | postcss: [/* your plugins */]
36 | }
37 | }
38 | ```
39 |
40 | See [vue-loader's related documentation](http://vuejs.github.io/vue-loader/en/features/postcss.html) for more details.
41 |
42 | ### Standalone CSS Files
43 |
44 | To ensure consistent extraction and processing, it is recommended to import global, standalone style files from your root `App.vue` component, for example:
45 |
46 | ``` html
47 |
48 |
49 | ```
50 |
51 | Note you should probably only do this for the styles written by yourself for your application. For existing libraries e.g. Bootstrap or Semantic UI, you can place them inside `/static` and reference them directly in `index.html`. This avoids extra build time and also is better for browser caching. (See [Static Asset Handling](static.md))
52 |
--------------------------------------------------------------------------------
/docs/prerender.md:
--------------------------------------------------------------------------------
1 | # Prerendering for SEO
2 |
3 | If you want to prerender routes that will not significantly change once pushed to production, use this Webpack plugin: [prerender-spa-plugin](https://www.npmjs.com/package/prerender-spa-plugin), which has been tested for use with Vue. For pages that _do_ frequently change, [Prerender.io](https://prerender.io/) and [Netlify](https://www.netlify.com/pricing) both offer plans for regularly re-prerendering your content for search engines.
4 |
5 | ## Using `prerender-spa-plugin`
6 |
7 | 1. Install it as a dev dependency:
8 |
9 | ```bash
10 | npm install --save-dev prerender-spa-plugin
11 | ```
12 |
13 | 2. Require it in **build/webpack.prod.conf.js**:
14 |
15 | ```js
16 | // This line should go at the top of the file where other 'imports' live in
17 | var PrerenderSpaPlugin = require('prerender-spa-plugin')
18 | ```
19 |
20 | 3. Configure it in the `plugins` array (also in **build/webpack.prod.conf.js**):
21 |
22 | ```js
23 | new PrerenderSpaPlugin(
24 | // Path to compiled app
25 | path.join(__dirname, '../dist'),
26 | // List of endpoints you wish to prerender
27 | [ '/' ]
28 | )
29 | ```
30 |
31 | If you also wanted to prerender `/about` and `/contact`, then that array would be `[ '/', '/about', '/contact' ]`.
32 |
33 | 4. Enable history mode for `vue-router`:
34 | ```js
35 | const router = new VueRouter({
36 | mode: 'history',
37 | routes: [...]
38 | })
39 | ```
40 |
--------------------------------------------------------------------------------
/docs/proxy.md:
--------------------------------------------------------------------------------
1 | # API Proxying During Development
2 |
3 | When integrating this boilerplate with an existing backend, a common need is to access the backend API when using the dev server. To achieve that, we can run the dev server and the API backend side-by-side (or remotely), and let the dev server proxy all API requests to the actual backend.
4 |
5 | To configure the proxy rules, edit `dev.proxyTable` option in `config/index.js`. The dev server is using [http-proxy-middleware](https://github.com/chimurai/http-proxy-middleware) for proxying, so you should refer to its docs for detailed usage. But here's a simple example:
6 |
7 | ``` js
8 | // config/index.js
9 | module.exports = {
10 | // ...
11 | dev: {
12 | proxyTable: {
13 | // proxy all requests starting with /api to jsonplaceholder
14 | '/api': {
15 | target: 'http://jsonplaceholder.typicode.com',
16 | changeOrigin: true,
17 | pathRewrite: {
18 | '^/api': ''
19 | }
20 | }
21 | }
22 | }
23 | }
24 | ```
25 |
26 | The above example will proxy the request `/api/posts/1` to `http://jsonplaceholder.typicode.com/posts/1`.
27 |
28 | ## URL Matching
29 |
30 | In addition to static urls you can also use glob patterns to match URLs, e.g. `/api/**`. See [Context Matching](https://github.com/chimurai/http-proxy-middleware#context-matching) for more details. In addition, you can provide a `filter` option that can be a custom function to determine whether a request should be proxied:
31 |
32 | ``` js
33 | proxyTable: {
34 | '**': {
35 | target: 'http://jsonplaceholder.typicode.com',
36 | filter: function (pathname, req) {
37 | return pathname.match('^/api') && req.method === 'GET'
38 | }
39 | }
40 | }
41 | ```
42 |
--------------------------------------------------------------------------------
/docs/static.md:
--------------------------------------------------------------------------------
1 | # Handling Static Assets
2 |
3 | You will notice in the project structure we have two directories for static assets: `src/assets` and `static/`. What is the difference between them?
4 |
5 | ### Webpacked Assets
6 |
7 | To answer this question, we first need to understand how Webpack deals with static assets. In `*.vue` components, all your templates and CSS are parsed by `vue-html-loader` and `css-loader` to look for asset URLs. For example, in `` and `background: url(./logo.png)`, `"./logo.png"` is a relative asset path and will be **resolved by Webpack as a module dependency**.
8 |
9 | Because `logo.png` is not JavaScript, when treated as a module dependency, we need to use `url-loader` and `file-loader` to process it. This boilerplate has already configured these loaders for you, so you basically get features such as filename fingerprinting and conditional base64 inlining for free, while being able to use relative/module paths without worrying about deployment.
10 |
11 | Since these assets may be inlined/copied/renamed during build, they are essentially part of your source code. This is why it is recommended to place Webpack-processed static assets inside `/src`, along side other source files. In fact, you don't even have to put them all in `/src/assets`: you can organize them based on the module/component using them. For example, you can put each component in its own directory, with its static assets right next to it.
12 |
13 | ### Asset Resolving Rules
14 |
15 | - **Relative URLs**, e.g. `./assets/logo.png` will be interpreted as a module dependency. They will be replaced with an auto-generated URL based on your Webpack output configuration.
16 |
17 | - **Non-prefixed URLs**, e.g. `assets/logo.png` will be treated the same as the relative URLs and translated into `./assets/logo.png`.
18 |
19 | - **URLs prefixed with `~`** are treated as a module request, similar to `require('some-module/image.png')`. You need to use this prefix if you want to leverage Webpack's module resolving configurations. For example if you have a resolve alias for `assets`, you need to use `
` to ensure that alias is respected.
20 |
21 | - **Root-relative URLs**, e.g. `/assets/logo.png` are not processed at all.
22 |
23 | ### Getting Asset Paths in JavaScript
24 |
25 | In order for Webpack to return the correct asset paths, you need to use `require('./relative/path/to/file.jpg')`, which will get processed by `file-loader` and returns the resolved URL. For example:
26 |
27 | ``` js
28 | computed: {
29 | background () {
30 | return require('./bgs/' + this.id + '.jpg')
31 | }
32 | }
33 | ```
34 |
35 | **Note the above example will include every image under `./bgs/` in the final build.** This is because Webpack cannot guess which of them will be used at runtime, so it includes them all.
36 |
37 | ### "Real" Static Assets
38 |
39 | In comparison, files in `static/` are not processed by Webpack at all: they are directly copied to their final destination as-is, with the same filename. You must reference these files using absolute paths, which is determined by joining `build.assetsPublicPath` and `build.assetsSubDirectory` in `config.js`.
40 |
41 | As an example, with the following default values:
42 |
43 | ``` js
44 | // config/index.js
45 | module.exports = {
46 | // ...
47 | build: {
48 | assetsPublicPath: '/',
49 | assetsSubDirectory: 'static'
50 | }
51 | }
52 | ```
53 |
54 | Any file placed in `static/` should be referenced using the absolute URL `/static/[filename]`. If you change `assetSubDirectory` to `assets`, then these URLs will need to be changed to `/assets/[filename]`.
55 |
56 | We will learn more about the config file in the section about [backend integration](backend.md).
57 |
--------------------------------------------------------------------------------
/docs/structure.md:
--------------------------------------------------------------------------------
1 | # Project Structure
2 |
3 | ``` bash
4 | .
5 | ├── build/ # webpack config files
6 | │ └── ...
7 | ├── config/
8 | │ ├── index.js # main project config
9 | │ └── ...
10 | ├── src/
11 | │ ├── main.js # app entry file
12 | │ ├── App.vue # main app component
13 | │ ├── components/ # ui components
14 | │ │ └── ...
15 | │ └── assets/ # module assets (processed by webpack)
16 | │ └── ...
17 | ├── static/ # pure static assets (directly copied)
18 | ├── test/
19 | │ └── unit/ # unit tests
20 | │ │ ├── specs/ # test spec files
21 | │ │ ├── index.js # test build entry file
22 | │ │ └── karma.conf.js # test runner config file
23 | │ └── e2e/ # e2e tests
24 | │ │ ├── specs/ # test spec files
25 | │ │ ├── custom-assertions/ # custom assertions for e2e tests
26 | │ │ ├── runner.js # test runner script
27 | │ │ └── nightwatch.conf.js # test runner config file
28 | ├── .babelrc # babel config
29 | ├── .postcssrc.js # postcss config
30 | ├── .eslintrc.js # eslint config
31 | ├── .editorconfig # editor config
32 | ├── index.html # index.html template
33 | └── package.json # build scripts and dependencies
34 | ```
35 |
36 | ### `build/`
37 |
38 | This directory holds the actual configurations for both the development server and the production webpack build. Normally you don't need to touch these files unless you want to customize Webpack loaders, in which case you should probably look at `build/webpack.base.conf.js`.
39 |
40 | ### `config/index.js`
41 |
42 | This is the main configuration file that exposes some of the most common configuration options for the build setup. See [API Proxying During Development](proxy.md) and [Integrating with Backend Framework](backend.md) for more details.
43 |
44 | ### `src/`
45 |
46 | This is where most of your application code will live in. How to structure everything inside this directory is largely up to you; if you are using Vuex, you can consult the [recommendations for Vuex applications](http://vuex.vuejs.org/en/structure.html).
47 |
48 | ### `static/`
49 |
50 | This directory is an escape hatch for static assets that you do not want to process with Webpack. They will be directly copied into the same directory where webpack-built assets are generated.
51 |
52 | See [Handling Static Assets](static.md) for more details.
53 |
54 | ### `test/unit`
55 |
56 | Contains unit test related files. See [Unit Testing](unit.md) for more details.
57 |
58 | ### `test/e2e`
59 |
60 | Contains e2e test related files. See [End-to-end Testing](e2e.md) for more details.
61 |
62 | ### `index.html`
63 |
64 | This is the **template** `index.html` for our single page application. During development and builds, Webpack will generate assets, and the URLs for those generated assets will be automatically injected into this template to render the final HTML.
65 |
66 | ### `package.json`
67 |
68 | The NPM package meta file that contains all the build dependencies and [build commands](commands.md).
69 |
--------------------------------------------------------------------------------
/docs/unit.md:
--------------------------------------------------------------------------------
1 | # Unit Testing
2 |
3 | An overview of the tools used by this boilerplate for unit testing:
4 |
5 | - [Karma](https://karma-runner.github.io/): the test runner that launches browsers, runs the tests and reports the results to us.
6 | - [karma-webpack](https://github.com/webpack/karma-webpack): the plugin for Karma that bundles our tests using Webpack.
7 | - [Mocha](https://mochajs.org/): the test framework that we write test specs with.
8 | - [Chai](http://chaijs.com/): test assertion library that provides better assertion syntax.
9 | - [Sinon](http://sinonjs.org/): test utility library that provides spies, stubs and mocks.
10 |
11 | Chai and Sinon are integrated using [karma-sinon-chai](https://github.com/kmees/karma-sinon-chai), so all Chai interfaces (`should`, `expect`, `assert`) and `sinon` are globally available in test files.
12 |
13 | And the files:
14 |
15 | - `index.js`
16 |
17 | This is the entry file used by `karma-webpack` to bundle all the test code and source code (for coverage purposes). You can ignore it for the most part.
18 |
19 | - `specs/`
20 |
21 | This directory is where you write your actual tests. You can use full ES2015+ and all supported Webpack loaders in your tests.
22 |
23 | - `karma.conf.js`
24 |
25 | This is the Karma configuration file. See [Karma docs](https://karma-runner.github.io/) for more details.
26 |
27 | ## Running Tests in More Browsers
28 |
29 | You can run the tests in multiple real browsers by installing more [karma launchers](https://karma-runner.github.io/1.0/config/browsers.html) and adjusting the `browsers` field in `test/unit/karma.conf.js`.
30 |
31 | ## Mocking Dependencies
32 |
33 | This boilerplate comes with [inject-loader](https://github.com/plasticine/inject-loader) installed by default. For usage with `*.vue` components, see [vue-loader docs on testing with mocks](http://vue-loader.vuejs.org/en/workflow/testing-with-mocks.html).
34 |
--------------------------------------------------------------------------------
/meta.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | "helpers": {
3 | "if_or": function (v1, v2, options) {
4 | if (v1 || v2) {
5 | return options.fn(this);
6 | }
7 |
8 | return options.inverse(this);
9 | }
10 | },
11 | "prompts": {
12 | "name": {
13 | "type": "string",
14 | "required": true,
15 | "message": "Project name"
16 | },
17 | "appid": {
18 | "type": "string",
19 | "required": false,
20 | "message": "wxmp appid",
21 | "default": "touristappid"
22 | },
23 | "description": {
24 | "type": "string",
25 | "required": false,
26 | "message": "Project description",
27 | "default": "A Mpvue project"
28 | },
29 | "author": {
30 | "type": "string",
31 | "message": "Author"
32 | },
33 | "build": {
34 | "type": "list",
35 | "message": "Vue build",
36 | "choices": [
37 | // {
38 | // "name": "Runtime + Compiler: recommended for most users",
39 | // "value": "standalone",
40 | // "short": "standalone"
41 | // },
42 | {
43 | "name": "Runtime-only: no custom render function, only can compile template in *.vue",
44 | "value": "runtime",
45 | "short": "runtime"
46 | }
47 | ]
48 | },
49 | "vuex": {
50 | "type": "confirm",
51 | "message": "Use Vuex?"
52 | },
53 | "lint": {
54 | "type": "confirm",
55 | "message": "Use ESLint to lint your code?"
56 | },
57 | // "lintConfig": {
58 | // "when": "lint",
59 | // "type": "list",
60 | // "message": "Pick an ESLint preset",
61 | // "choices": [
62 | // {
63 | // "name": "Standard (https://github.com/feross/standard)",
64 | // "value": "standard",
65 | // "short": "Standard"
66 | // },
67 | // {
68 | // "name": "Airbnb (https://github.com/airbnb/javascript)",
69 | // "value": "airbnb",
70 | // "short": "Airbnb"
71 | // },
72 | // {
73 | // "name": "none (configure it yourself)",
74 | // "value": "none",
75 | // "short": "none"
76 | // }
77 | // ]
78 | // },
79 | "test": {
80 | "value": false,
81 | "message": "小程序测试,敬请关注最新微信开发者工具的“测试报告”功能"
82 | }
83 | },
84 | "filters": {
85 | ".eslintrc.js": "lint",
86 | ".eslintignore": "lint",
87 | // "config/test.env.js": "unit || e2e",
88 | // "test/unit/**/*": "unit",
89 | // "build/webpack.test.conf.js": "unit",
90 | // "test/e2e/**/*": "e2e"
91 | "config/test.env.js": "test",
92 | "test/unit/**/*": "test",
93 | "build/webpack.test.conf.js": "test",
94 | "test/e2e/**/*": "test",
95 | "src/pages/counter/*": "vuex",
96 | },
97 | // "completeMessage": "To get started:\n\n {{^inPlace}}cd {{destDirName}}\n {{/inPlace}}npm install\n npm run dev\n\nDocumentation can be found at https://vuejs-templates.github.io/webpack"
98 | "completeMessage": "To get started:\n\n {{^inPlace}}cd {{destDirName}}\n {{/inPlace}}npm install\n npm run dev\n\nDocumentation can be found at http://mpvue.com"
99 | };
100 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "mpvue-quickstart",
3 | "version": "1.1.0",
4 | "license": "MIT",
5 | "description": "mpvue quickstart",
6 | "scripts": {
7 | "docs": "cd docs && gitbook serve",
8 | "docs:deploy": "bash ./deploy-docs.sh"
9 | },
10 | "devDependencies": {
11 | "vue-cli": "^2.8.2"
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/template/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | ["env", {
4 | "modules": false,
5 | "targets": {
6 | "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
7 | }
8 | }],
9 | "stage-2"
10 | ],
11 | "plugins": ["transform-runtime"],
12 | "env": {
13 | "test": {
14 | "presets": ["env", "stage-2"],
15 | "plugins": ["istanbul"]
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/template/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | indent_style = space
6 | indent_size = 2
7 | end_of_line = lf
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
--------------------------------------------------------------------------------
/template/.eslintignore:
--------------------------------------------------------------------------------
1 | build/*.js
2 | config/*.js
3 |
--------------------------------------------------------------------------------
/template/.eslintrc.js:
--------------------------------------------------------------------------------
1 | // http://eslint.org/docs/user-guide/configuring
2 |
3 | module.exports = {
4 | root: true,
5 | parser: 'babel-eslint',
6 | parserOptions: {
7 | sourceType: 'module'
8 | },
9 | env: {
10 | browser: false,
11 | node: true,
12 | es6: true
13 | },
14 | // https://github.com/standard/standard/blob/master/docs/RULES-en.md
15 | extends: 'standard',
16 | // required to lint *.vue files
17 | plugins: [
18 | 'html'
19 | ],
20 | // add your custom rules here
21 | 'rules': {
22 | // allow paren-less arrow functions
23 | 'arrow-parens': 0,
24 | // allow async-await
25 | 'generator-star-spacing': 0,
26 | // allow debugger during development
27 | 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
28 | },
29 | globals: {
30 | App: true,
31 | Page: true,
32 | wx: true,
33 | swan: true,
34 | tt: true,
35 | my: true,
36 | getApp: true,
37 | getPage: true,
38 | requirePlugin: true,
39 | mpvue: true,
40 | mpvuePlatform: true
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/template/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | node_modules/
3 | dist/
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | {{#unit}}
8 | test/unit/coverage
9 | {{/unit}}
10 | {{#e2e}}
11 | test/e2e/reports
12 | selenium-debug.log
13 | {{/e2e}}
14 |
15 | # Editor directories and files
16 | .idea
17 | *.suo
18 | *.ntvs*
19 | *.njsproj
20 | *.sln
21 |
--------------------------------------------------------------------------------
/template/.postcssrc.js:
--------------------------------------------------------------------------------
1 | // https://github.com/michael-ciniawsky/postcss-load-config
2 |
3 | module.exports = {
4 | "plugins": {
5 | "postcss-mpvue-wxss": {}
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/template/README.md:
--------------------------------------------------------------------------------
1 | # {{ name }}
2 |
3 | > {{ description }}
4 |
5 | ## Build Setup
6 |
7 | ``` bash
8 | # 初始化项目
9 | vue init mpvue/mpvue-quickstart myproject
10 | cd myproject
11 |
12 | # 安装依赖
13 | yarn
14 |
15 | # 开发时构建
16 | npm dev
17 |
18 | # 打包构建
19 | npm build
20 |
21 | # 指定平台的开发时构建(微信、百度、头条、支付宝)
22 | npm dev:wx
23 | npm dev:swan
24 | npm dev:tt
25 | npm dev:my
26 |
27 | # 指定平台的打包构建
28 | npm build:wx
29 | npm build:swan
30 | npm build:tt
31 | npm build:my
32 |
33 | # 生成 bundle 分析报告
34 | npm run build --report
35 | {{#unit}}
36 |
37 | # run unit tests
38 | npm run unit
39 | {{/unit}}
40 | {{#e2e}}
41 |
42 | # run e2e tests
43 | npm run e2e
44 | {{/e2e}}
45 | {{#if_or unit e2e}}
46 |
47 | # run all tests
48 | npm test
49 | {{/if_or}}
50 | ```
51 |
52 | For detailed explanation on how things work, checkout the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
53 |
--------------------------------------------------------------------------------
/template/build/build.js:
--------------------------------------------------------------------------------
1 | require('./check-versions')()
2 |
3 | process.env.NODE_ENV = 'production'
4 | process.env.PLATFORM = process.argv[process.argv.length - 1] || 'wx'
5 |
6 | var ora = require('ora')
7 | var rm = require('rimraf')
8 | var path = require('path')
9 | var chalk = require('chalk')
10 | var webpack = require('webpack')
11 | var config = require('../config')
12 | var webpackConfig = require('./webpack.prod.conf')
13 | var utils = require('./utils')
14 |
15 | var spinner = ora('building for production...')
16 | spinner.start()
17 |
18 | rm(path.join(config.build.assetsRoot, '*'), err => {
19 | if (err) throw err
20 | webpack(webpackConfig, function (err, stats) {
21 | spinner.stop()
22 | if (err) throw err
23 | if (process.env.PLATFORM === 'swan') {
24 | utils.writeFrameworkinfo()
25 | }
26 | process.stdout.write(stats.toString({
27 | colors: true,
28 | modules: false,
29 | children: false,
30 | chunks: false,
31 | chunkModules: false
32 | }) + '\n\n')
33 |
34 | if (stats.hasErrors()) {
35 | console.log(chalk.red(' Build failed with errors.\n'))
36 | process.exit(1)
37 | }
38 |
39 | console.log(chalk.cyan(' Build complete.\n'))
40 | console.log(chalk.yellow(
41 | ' Tip: built files are meant to be served over an HTTP server.\n' +
42 | ' Opening index.html over file:// won\'t work.\n'
43 | ))
44 | })
45 | })
46 |
--------------------------------------------------------------------------------
/template/build/check-versions.js:
--------------------------------------------------------------------------------
1 | var chalk = require('chalk')
2 | var semver = require('semver')
3 | var packageConfig = require('../package.json')
4 | var shell = require('shelljs')
5 | function exec (cmd) {
6 | return require('child_process').execSync(cmd).toString().trim()
7 | }
8 |
9 | var versionRequirements = [
10 | {
11 | name: 'node',
12 | currentVersion: semver.clean(process.version),
13 | versionRequirement: packageConfig.engines.node
14 | }
15 | ]
16 |
17 | if (shell.which('npm')) {
18 | versionRequirements.push({
19 | name: 'npm',
20 | currentVersion: exec('npm --version'),
21 | versionRequirement: packageConfig.engines.npm
22 | })
23 | }
24 |
25 | module.exports = function () {
26 | var warnings = []
27 | for (var i = 0; i < versionRequirements.length; i++) {
28 | var mod = versionRequirements[i]
29 | if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
30 | warnings.push(mod.name + ': ' +
31 | chalk.red(mod.currentVersion) + ' should be ' +
32 | chalk.green(mod.versionRequirement)
33 | )
34 | }
35 | }
36 |
37 | if (warnings.length) {
38 | console.log('')
39 | console.log(chalk.yellow('To use this template, you must update following to modules:'))
40 | console.log()
41 | for (var i = 0; i < warnings.length; i++) {
42 | var warning = warnings[i]
43 | console.log(' ' + warning)
44 | }
45 | console.log()
46 | process.exit(1)
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/template/build/dev-client.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable */
2 | require('eventsource-polyfill')
3 | var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true')
4 |
5 | hotClient.subscribe(function (event) {
6 | if (event.action === 'reload') {
7 | window.location.reload()
8 | }
9 | })
10 |
--------------------------------------------------------------------------------
/template/build/dev-server.js:
--------------------------------------------------------------------------------
1 | require('./check-versions')()
2 |
3 | process.env.PLATFORM = process.argv[process.argv.length - 1] || 'wx'
4 | var config = require('../config')
5 | if (!process.env.NODE_ENV) {
6 | process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
7 | }
8 |
9 | // var opn = require('opn')
10 | var path = require('path')
11 | var express = require('express')
12 | var webpack = require('webpack')
13 | var proxyMiddleware = require('http-proxy-middleware')
14 | var portfinder = require('portfinder')
15 | var webpackConfig = {{#if_or unit e2e}}(process.env.NODE_ENV === 'testing' || process.env.NODE_ENV === 'production')
16 | ? require('./webpack.prod.conf')
17 | : {{/if_or}}require('./webpack.dev.conf')
18 | var utils = require('./utils')
19 |
20 | // default port where dev server listens for incoming traffic
21 | var port = process.env.PORT || config.dev.port
22 | // automatically open browser, if not set will be false
23 | var autoOpenBrowser = !!config.dev.autoOpenBrowser
24 | // Define HTTP proxies to your custom API backend
25 | // https://github.com/chimurai/http-proxy-middleware
26 | var proxyTable = config.dev.proxyTable
27 |
28 | var app = express()
29 | var compiler = webpack(webpackConfig)
30 | if (process.env.PLATFORM === 'swan') {
31 | utils.writeFrameworkinfo()
32 | }
33 |
34 | // var devMiddleware = require('webpack-dev-middleware')(compiler, {
35 | // publicPath: webpackConfig.output.publicPath,
36 | // quiet: true
37 | // })
38 |
39 | // var hotMiddleware = require('webpack-hot-middleware')(compiler, {
40 | // log: false,
41 | // heartbeat: 2000
42 | // })
43 | // force page reload when html-webpack-plugin template changes
44 | // compiler.plugin('compilation', function (compilation) {
45 | // compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
46 | // hotMiddleware.publish({ action: 'reload' })
47 | // cb()
48 | // })
49 | // })
50 |
51 | // proxy api requests
52 | Object.keys(proxyTable).forEach(function (context) {
53 | var options = proxyTable[context]
54 | if (typeof options === 'string') {
55 | options = { target: options }
56 | }
57 | app.use(proxyMiddleware(options.filter || context, options))
58 | })
59 |
60 | // handle fallback for HTML5 history API
61 | app.use(require('connect-history-api-fallback')())
62 |
63 | // serve webpack bundle output
64 | // app.use(devMiddleware)
65 |
66 | // enable hot-reload and state-preserving
67 | // compilation error display
68 | // app.use(hotMiddleware)
69 |
70 | // serve pure static assets
71 | var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
72 | app.use(staticPath, express.static('./static'))
73 |
74 | // var uri = 'http://localhost:' + port
75 |
76 | var _resolve
77 | var readyPromise = new Promise(resolve => {
78 | _resolve = resolve
79 | })
80 |
81 | // console.log('> Starting dev server...')
82 | // devMiddleware.waitUntilValid(() => {
83 | // console.log('> Listening at ' + uri + '\n')
84 | // // when env is testing, don't need open it
85 | // if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
86 | // opn(uri)
87 | // }
88 | // _resolve()
89 | // })
90 |
91 | module.exports = new Promise((resolve, reject) => {
92 | portfinder.basePort = port
93 | portfinder.getPortPromise()
94 | .then(newPort => {
95 | if (port !== newPort) {
96 | console.log(`${port}端口被占用,开启新端口${newPort}`)
97 | }
98 | var server = app.listen(newPort, 'localhost')
99 | // for 小程序的文件保存机制
100 | require('webpack-dev-middleware-hard-disk')(compiler, {
101 | publicPath: webpackConfig.output.publicPath,
102 | quiet: true
103 | })
104 | resolve({
105 | ready: readyPromise,
106 | close: () => {
107 | server.close()
108 | }
109 | })
110 | }).catch(error => {
111 | console.log('没有找到空闲端口,请打开任务管理器杀死进程端口再试', error)
112 | })
113 | })
114 |
--------------------------------------------------------------------------------
/template/build/utils.js:
--------------------------------------------------------------------------------
1 | var path = require('path')
2 | var fs = require('fs')
3 | var config = require('../config')
4 | var ExtractTextPlugin = require('extract-text-webpack-plugin')
5 | var mpvueInfo = require('../node_modules/mpvue/package.json')
6 | var packageInfo = require('../package.json')
7 | var mkdirp = require('mkdirp')
8 |
9 | exports.assetsPath = function (_path) {
10 | var assetsSubDirectory = process.env.NODE_ENV === 'production'
11 | ? config.build.assetsSubDirectory
12 | : config.dev.assetsSubDirectory
13 | return path.posix.join(assetsSubDirectory, _path)
14 | }
15 |
16 | exports.cssLoaders = function (options) {
17 | options = options || {}
18 |
19 | var cssLoader = {
20 | loader: 'css-loader',
21 | options: {
22 | minimize: process.env.NODE_ENV === 'production',
23 | sourceMap: options.sourceMap
24 | }
25 | }
26 |
27 | var postcssLoader = {
28 | loader: 'postcss-loader',
29 | options: {
30 | sourceMap: true
31 | }
32 | }
33 |
34 | var px2rpxLoader = {
35 | loader: 'px2rpx-loader',
36 | options: {
37 | baseDpr: 1,
38 | rpxUnit: 0.5
39 | }
40 | }
41 |
42 | // generate loader string to be used with extract text plugin
43 | function generateLoaders (loader, loaderOptions) {
44 | var loaders = [cssLoader, px2rpxLoader, postcssLoader]
45 | if (loader) {
46 | loaders.push({
47 | loader: loader + '-loader',
48 | options: Object.assign({}, loaderOptions, {
49 | sourceMap: options.sourceMap
50 | })
51 | })
52 | }
53 |
54 | // Extract CSS when that option is specified
55 | // (which is the case during production build)
56 | if (options.extract) {
57 | return ExtractTextPlugin.extract({
58 | use: loaders,
59 | fallback: 'vue-style-loader'
60 | })
61 | } else {
62 | return ['vue-style-loader'].concat(loaders)
63 | }
64 | }
65 |
66 | // https://vue-loader.vuejs.org/en/configurations/extract-css.html
67 | return {
68 | css: generateLoaders(),
69 | wxss: generateLoaders(),
70 | postcss: generateLoaders(),
71 | less: generateLoaders('less'),
72 | sass: generateLoaders('sass', { indentedSyntax: true }),
73 | scss: generateLoaders('sass'),
74 | stylus: generateLoaders('stylus'),
75 | styl: generateLoaders('stylus')
76 | }
77 | }
78 |
79 | // Generate loaders for standalone style files (outside of .vue)
80 | exports.styleLoaders = function (options) {
81 | var output = []
82 | var loaders = exports.cssLoaders(options)
83 | for (var extension in loaders) {
84 | var loader = loaders[extension]
85 | output.push({
86 | test: new RegExp('\\.' + extension + '$'),
87 | use: loader
88 | })
89 | }
90 | return output
91 | }
92 |
93 | const writeFile = async (filePath, content) => {
94 | let dir = path.dirname(filePath)
95 | let exist = fs.existsSync(dir)
96 | if (!exist) {
97 | await mkdirp(dir)
98 | }
99 | await fs.writeFileSync(filePath, content, 'utf8')
100 | }
101 |
102 | exports.writeFrameworkinfo = function () {
103 | var buildInfo = {
104 | 'toolName': mpvueInfo.name,
105 | 'toolFrameWorkVersion': mpvueInfo.version,
106 | 'toolCliVersion': packageInfo.mpvueTemplateProjectVersion || '',
107 | 'createTime': Date.now()
108 | }
109 |
110 | var content = JSON.stringify(buildInfo)
111 | var fileName = '.frameworkinfo'
112 | var rootDir = path.resolve(__dirname, `../${fileName}`)
113 | var distDir = path.resolve(config.build.assetsRoot, `./${fileName}`)
114 |
115 | writeFile(rootDir, content)
116 | writeFile(distDir, content)
117 | }
118 |
--------------------------------------------------------------------------------
/template/build/vue-loader.conf.js:
--------------------------------------------------------------------------------
1 | var utils = require('./utils')
2 | var config = require('../config')
3 | // var isProduction = process.env.NODE_ENV === 'production'
4 | // for mp
5 | var isProduction = true
6 |
7 | module.exports = {
8 | loaders: utils.cssLoaders({
9 | sourceMap: isProduction
10 | ? config.build.productionSourceMap
11 | : config.dev.cssSourceMap,
12 | extract: isProduction
13 | }),
14 | transformToRequire: {
15 | video: 'src',
16 | source: 'src',
17 | img: 'src',
18 | image: 'xlink:href'
19 | },
20 | fileExt: config.build.fileExt
21 | }
22 |
--------------------------------------------------------------------------------
/template/build/webpack.base.conf.js:
--------------------------------------------------------------------------------
1 | var path = require('path')
2 | var fs = require('fs')
3 | var utils = require('./utils')
4 | var config = require('../config')
5 | var webpack = require('webpack')
6 | var merge = require('webpack-merge')
7 | var vueLoaderConfig = require('./vue-loader.conf')
8 | var MpvuePlugin = require('webpack-mpvue-asset-plugin')
9 | var glob = require('glob')
10 | var CopyWebpackPlugin = require('copy-webpack-plugin')
11 | var relative = require('relative')
12 |
13 | function resolve (dir) {
14 | return path.join(__dirname, '..', dir)
15 | }
16 |
17 | function getEntry (rootSrc) {
18 | var map = {};
19 | glob.sync(rootSrc + '/pages/**/main.js')
20 | .forEach(file => {
21 | var key = relative(rootSrc, file).replace('.js', '');
22 | map[key] = file;
23 | })
24 | return map;
25 | }
26 |
27 | const appEntry = { app: resolve('./src/main.js') }
28 | const pagesEntry = getEntry(resolve('./src'), 'pages/**/main.js')
29 | const entry = Object.assign({}, appEntry, pagesEntry)
30 |
31 | let baseWebpackConfig = {
32 | // 如果要自定义生成的 dist 目录里面的文件路径,
33 | // 可以将 entry 写成 {'toPath': 'fromPath'} 的形式,
34 | // toPath 为相对于 dist 的路径, 例:index/demo,则生成的文件地址为 dist/index/demo.js
35 | entry,
36 | target: require('mpvue-webpack-target'),
37 | output: {
38 | path: config.build.assetsRoot,
39 | jsonpFunction: 'webpackJsonpMpvue',
40 | filename: '[name].js',
41 | publicPath: process.env.NODE_ENV === 'production'
42 | ? config.build.assetsPublicPath
43 | : config.dev.assetsPublicPath
44 | },
45 | resolve: {
46 | extensions: ['.js', '.vue', '.json'],
47 | alias: {
48 | {{#if_eq build "standalone"}}
49 | // 'vue$': `vue/dist/${config.build.fileExt.platform}/vue.esm.js`,
50 | {{/if_eq}}
51 | 'vue': 'mpvue',
52 | '@': resolve('src')
53 | },
54 | symlinks: false,
55 | aliasFields: ['mpvue', 'weapp', 'browser'],
56 | mainFields: ['browser', 'module', 'main']
57 | },
58 | module: {
59 | rules: [
60 | {{#lint}}
61 | {
62 | test: /\.(js|vue)$/,
63 | loader: 'eslint-loader',
64 | enforce: 'pre',
65 | include: [resolve('src'), resolve('test')],
66 | options: {
67 | formatter: require('eslint-friendly-formatter')
68 | }
69 | },
70 | {{/lint}}
71 | {
72 | test: /\.vue$/,
73 | loader: 'mpvue-loader',
74 | options: vueLoaderConfig
75 | },
76 | {
77 | test: /\.js$/,
78 | include: [resolve('src'), resolve('test')],
79 | use: [
80 | 'babel-loader',
81 | {
82 | loader: 'mpvue-loader',
83 | options: Object.assign({checkMPEntry: true}, vueLoaderConfig)
84 | },
85 | ]
86 | },
87 | {
88 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
89 | loader: 'url-loader',
90 | options: {
91 | limit: 10000,
92 | name: utils.assetsPath('img/[name].[ext]')
93 | }
94 | },
95 | {
96 | test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
97 | loader: 'url-loader',
98 | options: {
99 | limit: 10000,
100 | name: utils.assetsPath('media/[name].[ext]')
101 | }
102 | },
103 | {
104 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
105 | loader: 'url-loader',
106 | options: {
107 | limit: 10000,
108 | name: utils.assetsPath('fonts/[name].[ext]')
109 | }
110 | }
111 | ]
112 | },
113 | plugins: [
114 | // api 统一桥协议方案
115 | new webpack.DefinePlugin({
116 | 'mpvue': 'global.mpvue',
117 | 'mpvuePlatform': 'global.mpvuePlatform'
118 | }),
119 | new MpvuePlugin(),
120 | new CopyWebpackPlugin([{
121 | from: '**/*.json',
122 | to: ''
123 | }], {
124 | context: 'src/'
125 | }),
126 | new CopyWebpackPlugin([
127 | {
128 | from: path.resolve(__dirname, '../static'),
129 | to: path.resolve(config.build.assetsRoot, './static'),
130 | ignore: ['.*']
131 | }
132 | ])
133 | ]
134 | }
135 |
136 | // 针对百度小程序,由于不支持通过 miniprogramRoot 进行自定义构建完的文件的根路径
137 | // 所以需要将项目根路径下面的 project.swan.json 拷贝到构建目录
138 | // 然后百度开发者工具将 dist/swan 作为项目根目录打
139 | const projectConfigMap = {
140 | tt: '../project.config.json',
141 | swan: '../project.swan.json'
142 | }
143 |
144 | const PLATFORM = process.env.PLATFORM
145 | if (/^(swan)|(tt)$/.test(PLATFORM)) {
146 | baseWebpackConfig = merge(baseWebpackConfig, {
147 | plugins: [
148 | new CopyWebpackPlugin([{
149 | from: path.resolve(__dirname, projectConfigMap[PLATFORM]),
150 | to: path.resolve(config.build.assetsRoot)
151 | }])
152 | ]
153 | })
154 | }
155 |
156 | module.exports = baseWebpackConfig
157 |
--------------------------------------------------------------------------------
/template/build/webpack.dev.conf.js:
--------------------------------------------------------------------------------
1 | var utils = require('./utils')
2 | var webpack = require('webpack')
3 | var config = require('../config')
4 | var merge = require('webpack-merge')
5 | var baseWebpackConfig = require('./webpack.base.conf')
6 | // var HtmlWebpackPlugin = require('html-webpack-plugin')
7 | var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
8 | var MpvueVendorPlugin = require('webpack-mpvue-vendor-plugin')
9 |
10 | // copy from ./webpack.prod.conf.js
11 | var path = require('path')
12 | var ExtractTextPlugin = require('extract-text-webpack-plugin')
13 | var CopyWebpackPlugin = require('copy-webpack-plugin')
14 | var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
15 |
16 | // add hot-reload related code to entry chunks
17 | // Object.keys(baseWebpackConfig.entry).forEach(function (name) {
18 | // baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
19 | // })
20 |
21 | module.exports = merge(baseWebpackConfig, {
22 | module: {
23 | rules: utils.styleLoaders({
24 | sourceMap: config.dev.cssSourceMap,
25 | extract: true
26 | })
27 | },
28 | // cheap-module-eval-source-map is faster for development
29 | // devtool: '#cheap-module-eval-source-map',
30 | // devtool: '#source-map',
31 | output: {
32 | path: config.build.assetsRoot,
33 | // filename: utils.assetsPath('[name].[chunkhash].js'),
34 | // chunkFilename: utils.assetsPath('[id].[chunkhash].js')
35 | filename: utils.assetsPath('[name].js'),
36 | chunkFilename: utils.assetsPath('[id].js')
37 | },
38 | plugins: [
39 | new webpack.DefinePlugin({
40 | 'process.env': config.dev.env
41 | }),
42 |
43 | // copy from ./webpack.prod.conf.js
44 | // extract css into its own file
45 | new ExtractTextPlugin({
46 | // filename: utils.assetsPath('[name].[contenthash].css')
47 | filename: utils.assetsPath(`[name].${config.dev.fileExt.style}`)
48 | }),
49 | // Compress extracted CSS. We are using this plugin so that possible
50 | // duplicated CSS from different components can be deduped.
51 | new OptimizeCSSPlugin({
52 | cssProcessorOptions: {
53 | safe: true
54 | }
55 | }),
56 | new webpack.optimize.CommonsChunkPlugin({
57 | name: 'common/vendor',
58 | minChunks: function (module, count) {
59 | // any required modules inside node_modules are extracted to vendor
60 | return (
61 | module.resource &&
62 | /\.js$/.test(module.resource) &&
63 | module.resource.indexOf('node_modules') >= 0
64 | ) || count > 1
65 | }
66 | }),
67 | new webpack.optimize.CommonsChunkPlugin({
68 | name: 'common/manifest',
69 | chunks: ['common/vendor']
70 | }),
71 | new MpvueVendorPlugin({
72 | platform: process.env.PLATFORM
73 | }),
74 | // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
75 | // new webpack.HotModuleReplacementPlugin(),
76 | new webpack.NoEmitOnErrorsPlugin(),
77 | // https://github.com/ampedandwired/html-webpack-plugin
78 | // new HtmlWebpackPlugin({
79 | // filename: 'index.html',
80 | // template: 'index.html',
81 | // inject: true
82 | // }),
83 | new FriendlyErrorsPlugin()
84 | ]
85 | })
86 |
--------------------------------------------------------------------------------
/template/build/webpack.prod.conf.js:
--------------------------------------------------------------------------------
1 | var path = require('path')
2 | var utils = require('./utils')
3 | var webpack = require('webpack')
4 | var config = require('../config')
5 | var merge = require('webpack-merge')
6 | var baseWebpackConfig = require('./webpack.base.conf')
7 | var UglifyJsPlugin = require('uglifyjs-webpack-plugin')
8 | var CopyWebpackPlugin = require('copy-webpack-plugin')
9 | // var HtmlWebpackPlugin = require('html-webpack-plugin')
10 | var ExtractTextPlugin = require('extract-text-webpack-plugin')
11 | var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
12 | var MpvueVendorPlugin = require('webpack-mpvue-vendor-plugin')
13 | var env = {{#if_or unit e2e}}process.env.NODE_ENV === 'testing'
14 | ? require('../config/test.env')
15 | : {{/if_or}}config.build.env
16 |
17 | var webpackConfig = merge(baseWebpackConfig, {
18 | module: {
19 | rules: utils.styleLoaders({
20 | sourceMap: config.build.productionSourceMap,
21 | extract: true
22 | })
23 | },
24 | devtool: config.build.productionSourceMap ? '#source-map' : false,
25 | output: {
26 | path: config.build.assetsRoot,
27 | // filename: utils.assetsPath('[name].[chunkhash].js'),
28 | // chunkFilename: utils.assetsPath('[id].[chunkhash].js')
29 | filename: utils.assetsPath('[name].js'),
30 | chunkFilename: utils.assetsPath('[id].js')
31 | },
32 | plugins: [
33 | // http://vuejs.github.io/vue-loader/en/workflow/production.html
34 | new webpack.DefinePlugin({
35 | 'process.env': env
36 | }),
37 | // extract css into its own file
38 | new ExtractTextPlugin({
39 | // filename: utils.assetsPath('[name].[contenthash].css')
40 | filename: utils.assetsPath(`[name].${config.build.fileExt.style}`)
41 | }),
42 | // Compress extracted CSS. We are using this plugin so that possible
43 | // duplicated CSS from different components can be deduped.
44 | new OptimizeCSSPlugin({
45 | cssProcessorOptions: {
46 | safe: true
47 | }
48 | }),
49 | // generate dist index.html with correct asset hash for caching.
50 | // you can customize output by editing /index.html
51 | // see https://github.com/ampedandwired/html-webpack-plugin
52 | // new HtmlWebpackPlugin({
53 | // filename: {{#if_or unit e2e}}process.env.NODE_ENV === 'testing'
54 | // ? 'index.html'
55 | // : {{/if_or}}config.build.index,
56 | // template: 'index.html',
57 | // inject: true,
58 | // minify: {
59 | // removeComments: true,
60 | // collapseWhitespace: true,
61 | // removeAttributeQuotes: true
62 | // // more options:
63 | // // https://github.com/kangax/html-minifier#options-quick-reference
64 | // },
65 | // // necessary to consistently work with multiple chunks via CommonsChunkPlugin
66 | // chunksSortMode: 'dependency'
67 | // }),
68 | // keep module.id stable when vender modules does not change
69 | new webpack.HashedModuleIdsPlugin(),
70 | // split vendor js into its own file
71 | new webpack.optimize.CommonsChunkPlugin({
72 | name: 'common/vendor',
73 | minChunks: function (module, count) {
74 | // any required modules inside node_modules are extracted to vendor
75 | return (
76 | module.resource &&
77 | /\.js$/.test(module.resource) &&
78 | module.resource.indexOf('node_modules') >= 0
79 | ) || count > 1
80 | }
81 | }),
82 | // extract webpack runtime and module manifest to its own file in order to
83 | // prevent vendor hash from being updated whenever app bundle is updated
84 | new webpack.optimize.CommonsChunkPlugin({
85 | name: 'common/manifest',
86 | chunks: ['common/vendor']
87 | }),
88 | new MpvueVendorPlugin({
89 | platform: process.env.PLATFORM
90 | })
91 | ]
92 | })
93 |
94 | // if (config.build.productionGzip) {
95 | // var CompressionWebpackPlugin = require('compression-webpack-plugin')
96 |
97 | // webpackConfig.plugins.push(
98 | // new CompressionWebpackPlugin({
99 | // asset: '[path].gz[query]',
100 | // algorithm: 'gzip',
101 | // test: new RegExp(
102 | // '\\.(' +
103 | // config.build.productionGzipExtensions.join('|') +
104 | // ')$'
105 | // ),
106 | // threshold: 10240,
107 | // minRatio: 0.8
108 | // })
109 | // )
110 | // }
111 |
112 | if (config.build.bundleAnalyzerReport) {
113 | var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
114 | webpackConfig.plugins.push(new BundleAnalyzerPlugin())
115 | }
116 |
117 | var useUglifyJs = process.env.PLATFORM !== 'swan'
118 | if (useUglifyJs) {
119 | webpackConfig.plugins.push(new UglifyJsPlugin({
120 | sourceMap: true
121 | }))
122 | }
123 |
124 | module.exports = webpackConfig
125 |
--------------------------------------------------------------------------------
/template/build/webpack.test.conf.js:
--------------------------------------------------------------------------------
1 | // This is the webpack config used for unit tests.
2 |
3 | var utils = require('./utils')
4 | var webpack = require('webpack')
5 | var merge = require('webpack-merge')
6 | var baseConfig = require('./webpack.base.conf')
7 |
8 | var webpackConfig = merge(baseConfig, {
9 | // use inline sourcemap for karma-sourcemap-loader
10 | module: {
11 | rules: utils.styleLoaders()
12 | },
13 | devtool: '#inline-source-map',
14 | resolveLoader: {
15 | alias: {
16 | // necessary to to make lang="scss" work in test when using vue-loader's ?inject option
17 | // see discussion at https://github.com/vuejs/vue-loader/issues/724
18 | 'scss-loader': 'sass-loader'
19 | }
20 | },
21 | plugins: [
22 | new webpack.DefinePlugin({
23 | 'process.env': require('../config/test.env')
24 | })
25 | ]
26 | })
27 |
28 | // no need for app entry during tests
29 | delete webpackConfig.entry
30 |
31 | module.exports = webpackConfig
32 |
--------------------------------------------------------------------------------
/template/config/dev.env.js:
--------------------------------------------------------------------------------
1 | var merge = require('webpack-merge')
2 | var prodEnv = require('./prod.env')
3 |
4 | module.exports = merge(prodEnv, {
5 | NODE_ENV: '"development"'
6 | })
7 |
--------------------------------------------------------------------------------
/template/config/index.js:
--------------------------------------------------------------------------------
1 | // see http://vuejs-templates.github.io/webpack for documentation.
2 | var path = require('path')
3 | var fileExtConfig = {
4 | swan: {
5 | template: 'swan',
6 | script: 'js',
7 | style: 'css',
8 | platform: 'swan'
9 | },
10 | tt: {
11 | template: 'ttml',
12 | script: 'js',
13 | style: 'ttss',
14 | platform: 'tt'
15 | },
16 | wx: {
17 | template: 'wxml',
18 | script: 'js',
19 | style: 'wxss',
20 | platform: 'wx'
21 | },
22 | my: {
23 | template: 'axml',
24 | script: 'js',
25 | style: 'acss',
26 | platform: 'my'
27 | }
28 | }
29 | var fileExt = fileExtConfig[process.env.PLATFORM]
30 |
31 | module.exports = {
32 | build: {
33 | env: require('./prod.env'),
34 | index: path.resolve(__dirname, `../dist/${fileExt.platform}/index.html`),
35 | assetsRoot: path.resolve(__dirname, `../dist/${fileExt.platform}`),
36 | assetsSubDirectory: '',
37 | assetsPublicPath: '/',
38 | productionSourceMap: false,
39 | // Gzip off by default as many popular static hosts such as
40 | // Surge or Netlify already gzip all static assets for you.
41 | // Before setting to `true`, make sure to:
42 | // npm install --save-dev compression-webpack-plugin
43 | productionGzip: false,
44 | productionGzipExtensions: ['js', 'css'],
45 | // Run the build command with an extra argument to
46 | // View the bundle analyzer report after build finishes:
47 | // `npm run build --report`
48 | // Set to `true` or `false` to always turn it on or off
49 | bundleAnalyzerReport: process.env.npm_config_report,
50 | fileExt: fileExt
51 | },
52 | dev: {
53 | env: require('./dev.env'),
54 | port: 8080,
55 | // 在小程序开发者工具中不需要自动打开浏览器
56 | autoOpenBrowser: false,
57 | assetsSubDirectory: '',
58 | assetsPublicPath: '/',
59 | proxyTable: {},
60 | // CSS Sourcemaps off by default because relative paths are "buggy"
61 | // with this option, according to the CSS-Loader README
62 | // (https://github.com/webpack/css-loader#sourcemaps)
63 | // In our experience, they generally work as expected,
64 | // just be aware of this issue when enabling this option.
65 | cssSourceMap: false,
66 | fileExt: fileExt
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/template/config/prod.env.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | NODE_ENV: '"production"'
3 | }
4 |
--------------------------------------------------------------------------------
/template/config/test.env.js:
--------------------------------------------------------------------------------
1 | var merge = require('webpack-merge')
2 | var devEnv = require('./dev.env')
3 |
4 | module.exports = merge(devEnv, {
5 | NODE_ENV: '"testing"'
6 | })
7 |
--------------------------------------------------------------------------------
/template/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | \{{text}} 5 |
6 |Vuex counter:\{{ count }}
4 |5 | 6 | 7 |
8 |