vue官方vue-cli构建的vue项目结构分析

时间:2019-02-20
本文章向大家介绍vue官方vue-cli构建的vue项目结构分析,主要包括vue官方vue-cli构建的vue项目结构分析使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、概要

vue现在在很多公司会大量使用,研究一下vue-cli脚手架构建项目的项目结构,有助于理解vue。

博客首发地址:https://www.mwcxs.top/page/570.html

使用vue-cli脚手架搭建vue项目的具体步骤如下:

npm install -g vue-cli
cd E:(跳转到项目目录)
vue init webpack vueproject (vueproject 为项目目录名称,可行更改)
cd vueproject
npm install
npm run dev

 

二、具体分析

2.1package.json文件

1、script字段

  "scripts": {
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "start": "npm run dev",
    "unit": "jest --config test/unit/jest.conf.js --coverage",
    "e2e": "node test/e2e/runner.js",
    "test": "npm run unit && npm run e2e",
    "lint": "eslint --ext .js,.vue src test/unit test/e2e/specs",
    "build": "node build/build.js"
  },

项目开发周期主要执行的两个任务分别是开发环境npm run dev和打包任务npm run build,script字段是用来指定npm相关命令的缩写的

npm run dev 其实执行的是

webpack-dev-server --inline --progress --config build/webpack.dev.conf.js

利用 webpack-dev-server 读取 webpack.dev.conf.js 信息并启动一个本地服务器,这应该也是新版本vue-cli的新特性。

以前老的项目是使用node的express开启一个本地服务器。 

2、dependencies和devDependencies字段

dependencies字段指定了项目运行时所依赖的模块;

devDependencies字段是指定了项目开发时候所依赖的模块。

项目开发应使用的命令管理package.json文件:

npm i --save vue      //自动写入到dependencies字段中
npm i --save-dev babel-core        //自动写入到devDependencies字段

3、engines和browerslist字段

 "engines": {
    "node": ">= 6.0.0",
    "npm": ">= 3.0.0"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ]

engines字段表示项目运行的所依赖的node以及npm的版本号;

browserslist表示项目的浏览器支持情况。

 

 

2.2build文件夹

1、基础配置文件 webpack.base.conf.js 

基础的webpack配置文件主要根据模式(开发,线上等)定义了入口和出口,以及处理vue,babel等的各种模块,是最基础的部分。其他模式(开发,线上等)的配置文件是以base为基础通过webpack-merge合并的。

'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {  //处理路径
  return path.join(__dirname, '..', dir)
}

const createLintingRule = () => ({  //Eslint检查规则
  test: /\.(js|vue)$/,
  loader: 'eslint-loader',
  enforce: 'pre',
  include: [resolve('src'), resolve('test')],
  options: {
    formatter: require('eslint-friendly-formatter'),
    emitWarning: !config.dev.showEslintErrorsInOverlay
  }
})

module.exports = {   
  context: path.resolve(__dirname, '../'),     //基础目录
  entry: {
    app: './src/main.js'   //入口文件
  },
  output: {
    path: config.build.assetsRoot,    //输出文件,默认为../dist
    filename: '[name].js',            //输出文件名称
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath   //生成模式publicpath
      : config.dev.assetsPublicPath     //开发模式
  },
  resolve: {     //解析确定的扩展名,方便模块导入
    extensions: ['.js', '.vue', '.json'],
    alias: {     //创建别名
      'vue$': 'vue/dist/vue.esm.js',        '@': resolve('src'),   //如‘@/components/helloWorld’    } },
module: {      //模块相关配置,包括loader,plugin等
    rules: [
      ...(config.dev.useEslint ? [createLintingRule()] : []),
      {
        test: /\.vue$/,     //vue要在babel之前
        loader: 'vue-loader',   //vue转成普通的html
        options: vueLoaderConfig   //可选项:vue-loader选项配置
      },
      {
        test: /\.js$/,    //babel
        loader: 'babel-loader',   //es6转es5 的loader
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      {          //url-loader 文件大小低于指定的限制时,可返回DataURL,即base64
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,    //url-loader图片
        loader: 'url-loader',
        options: {         //兼容性问题需要将query换成options
          limit: 10000,    //默认没有限制
          name: utils.assetsPath('img/[name].[hash:7].[ext]')     //hash: 7da代表7位数的hash
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,       //url-loader音视频
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,     //url-loader 字体
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  node: {    //是否polyfill或mock
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}

webpack.base.conf.js主要完成了下面这些事情:

(1)配置webpack编译入口

(2)配置webpack输出路径和命名规则

(3)配置模块resolve规则

(4)配置不同类型模块的处理规则

注:这个配置里面只配置了.js、.vue、图片、字体等文件的处理规则,如果需要处理其他文件可以在module.rules里面配置

 

2、开发环境配置文件 webpack.dev.conf.js 

在启动项目的时候就要用到这个文件,说明这个文件比较重要

'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')    //基本参数配置
const merge = require('webpack-merge')   //用于合并webpack的base配置
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')  //webpack基本配置文件(开发时和运行时公用)
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')   //依据一个简单的模板,帮你生成最终的html文件,这个文件中自动引用你打包之后的js文件,每次编译都会插入一个不同的哈希值
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')   //能够更好的在终端看到webpack运行的警告和错误
const portfinder = require('portfinder')   //自动检索下一个可用端口

const HOST = process.env.HOST    //读取系统环境变量的host
const PORT = process.env.PORT && Number(process.env.PORT)   //读取系统环境变量的port

const devWebpackConfig = merge(baseWebpackConfig, {    //合并baseWebpackConfig配置
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })     //对一些独立的css文件以及他的预处理做一个编译
  },
  // cheap-module-eval-source-map is faster for development
  devtool: config.dev.devtool,     //添加原信息增强调试

  // these devServer options should be customized in /config/index.js
  devServer: {             //webpack-dev-server服务器配置
    clientLogLevel: 'warning',     //console控制台显示消息,可能的值有none,error,warning,info
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    hot: true,     //开启热加载
    contentBase: false, // since we use CopyWebpackPlugin.
    compress: true,    //开启压缩
    host: HOST || config.dev.host,  //process.env优先
    port: PORT || config.dev.port,  //process.env优先
    open: config.dev.autoOpenBrowser,    //自动打开浏览器,这里默认是false
    overlay: config.dev.errorOverlay     //warning和error都要显示
      ? { warnings: false, errors: true } 
      : false,
    publicPath: config.dev.assetsPublicPath,
    proxy: config.dev.proxyTable,      //代理设置,用于前后端分离
    quiet: true, // necessary for FriendlyErrorsPlugin
    watchOptions: {     //启用watch模式,这意味着初始构建之后,webpack将继续监听任何已解析文件的更改
      poll: config.dev.poll,    //通过传递true开启polling,或者指定毫秒为单位进行轮询,默认为false
    }
  },
  plugins: [    //webpack一些构建用到的插件
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env')
    }),
    new webpack.HotModuleReplacementPlugin(),   //模块热更新,它允许在运行的时候更新各个模块,而无需进行完全的刷新
    new webpack.NamedModulesPlugin(),  //热加载的时候直接返回更新的文件名,而不是id HMR shows correct file names in console on update.    new webpack.NoEmitOnErrorsPlugin(),    //跳过热编译是出错的代码并记录下来,主要作用是编译后运行的时候包不出错
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',    //指定编译后生成的html文件名
      template: 'index.html',    //需要处理的模板
      inject: true    //打包过程中的输出js,css的路径添加到html中,css文件插入到head中,js文件插入到body中,可能的选项有true,‘head’,‘body’,false
    }),
    // copy custom static assets
    new CopyWebpackPlugin([    //拷贝静态文档
      {
        from: path.resolve(__dirname, '../static'),
        to: config.dev.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = process.env.PORT || config.dev.port   //获取当前设定的端口
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      // publish the new Port, necessary for e2e tests
      process.env.PORT = port     //process发布的端口
      // add port to devServer config
      devWebpackConfig.devServer.port = port   //设置devserver端口

      // Add FriendlyErrorsPlugin
      devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({  //错误提示插件
        compilationSuccessInfo: {
          messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors
        ? utils.createNotifierCallback()
        : undefined
      }))

      resolve(devWebpackConfig)
    }
  })
})

该文件主要完成的事情:

(1)将hot-reload相关代码添加到entry chunks

(2)合并基础的webpack配置

(3)使用styleLoaders

(4)配置Source Maps

(5)配置webpack插件

 

3、生产模式配置文件 webpack.prod.conf.js

'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

const env = process.env.NODE_ENV === 'testing'
  ? require('../config/test.env')
  : require('../config/prod.env')

const webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,   //production下生成sourceMap
      extract: true,    //util中styleLoader方法内的generateLoaders函数
      usePostCSS: true    //默认使用postcss
    })
  },
  devtool: config.build.productionSourceMap ? config.build.devtool : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new UglifyJsPlugin({    //js代码压缩还可以配置include,cache等,也可以使用babel-minify
      uglifyOptions: {
        compress: {
          warnings: false
        }
      },
      sourceMap: config.build.productionSourceMap,
      parallel: true    //充分利用多核cpu
    }),
    // extract css into its own file
    new ExtractTextPlugin({    //提取js文件中的css
      filename: utils.assetsPath('css/[name].[contenthash].css'),
      // Setting the following option to `false` will not extract CSS from codesplit chunks.
      // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
      // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`, 
      // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
      allChunks: true,
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({     //压缩提取出来的css
      cssProcessorOptions: config.build.productionSourceMap
        ? { safe: true, map: { inline: false } }
        : { safe: true }
    }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({    //生成html
      filename: process.env.NODE_ENV === 'testing'
        ? 'index.html'
        : config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'    //按照dependency的顺序引入
    }),
    // keep module.id stable when vendor modules does not change
    new webpack.HashedModuleIdsPlugin(),   //根据模块的相对路径生成一个四位数的hash
    // enable scope hoisting
    new webpack.optimize.ModuleConcatenationPlugin(),  //预编译所有的模块到一个闭包中
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({   //拆分公共模块
      name: 'vendor',
      minChunks (module) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity
    }),
    // This instance extracts shared chunks from code splitted chunks and bundles them
    // in a separate chunk, similar to the vendor chunk
    // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
    new webpack.optimize.CommonsChunkPlugin({
      name: 'app',
      async: 'vendor-async',
      children: true,
      minChunks: 3
    }),

    // copy custom static assets
    new CopyWebpackPlugin([    //拷贝静态文档
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {   //开启gzip压缩
  const CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,   //10kb以上的文件才压缩
      minRatio: 0.8   //最小比例达到0.8时才压缩
    })
  )
}

if (config.build.bundleAnalyzerReport) {   //可视化分析包的尺寸
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

该文件的主要用处:

(1)合并基础的webpack.base.conf.js文件配置

(2)使用styleLoader

(3)配置webpack的输出路径

(4)配置webpack插件

(5)gzip模式下的webpack插件配置

(6)webpack-bundle分析

注:

webpack插件里面使用了压缩代码以及抽离css文件等插件

 

 

4、build.js 编译入口

'use strict'
require('./check-versions')()

process.env.NODE_ENV = 'production'    //设置当前环境为生产环境

const ora = require('ora')     //loading进度条
const rm = require('rimraf')   //删除文件 rm -rf
const path = require('path') 
const chalk = require('chalk')   //stdout颜色设置
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')

const spinner = ora('building for production...')
spinner.start()

rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {    //清空文件夹
  if (err) throw err
  webpack(webpackConfig, (err, stats) => {   //删除完成回调函数内执行编译
    spinner.stop()
    if (err) throw err
    process.stdout.write(stats.toString({    //编译完成,输出编译文件
      colors: true,
      modules: false,
      children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
      chunks: false,
      chunkModules: false
    }) + '\n\n')

    if (stats.hasErrors()) {   //error
      console.log(chalk.red('  Build failed with errors.\n'))
      process.exit(1)
    }

    console.log(chalk.cyan('  Build complete.\n'))  //完成
    console.log(chalk.yellow(
      '  Tip: built files are meant to be served over an HTTP server.\n' +
      '  Opening index.html over file:// won\'t work.\n'
    ))
  })
})

build.js主要作用为:

(1)显示打包的loading动画

(2)删除并创建目标文件夹

(3)webpack编译源文件

(4)输出打包后的文件

注:webpack编译后会输出到配置里面的目标文件夹;删除目标文件夹之后再创建是为了去除旧的内容,以免产生不可预测的影响

 

5、实用代码段utils.js

'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json')

exports.assetsPath = function (_path) {
  const assetsSubDirectory = process.env.NODE_ENV === 'production'
    ? config.build.assetsSubDirectory   //static
    : config.dev.assetsSubDirectory

  return path.posix.join(assetsSubDirectory, _path)   //posix方法修正路径
}

exports.cssLoaders = function (options) {
  options = options || {}

  const cssLoader = {    //csssloader
    loader: 'css-loader',
    options: {
      sourceMap: options.sourceMap
    }
  }

  const postcssLoader = {   //postcssloader
    loader: 'postcss-loader',
    options: {
      sourceMap: options.sourceMap
    }
  }

  // generate loader string to be used with extract text plugin
  function generateLoaders (loader, loaderOptions) {   //生成loader
    const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]

    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }

    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {    //生产模式中提取css
      return ExtractTextPlugin.extract({   //如果options的extract为true配合生成模式
        use: loaders,
        fallback: 'vue-style-loader'  //默认使用vue-style-loader
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }

  // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  return {   //返回各种loaders对象
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    sass: generateLoaders('sass', { indentedSyntax: true }),
    scss: generateLoaders('sass'),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  }
}
// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
  const output = []
  const loaders = exports.cssLoaders(options)

  for (const extension in loaders) {
    const loader = loaders[extension]
    output.push({
      test: new RegExp('\\.' + extension + '$'),
      use: loader
    })
  }

  return output
}

exports.createNotifierCallback = () => {  //配合friendly-errors-webpack-plugin
  const notifier = require('node-notifier')   //发送跨平台通知系统

  return (severity, errors) => {    //当前设定是只有出现error错误时触发notifier发送通知
    if (severity !== 'error') return   //严重程度可以是error或者warning

    const error = errors[0]
    const filename = error.file && error.file.split('!').pop()

    notifier.notify({
      title: packageConfig.name,
      message: severity + ': ' + error.name,
      subtitle: filename || '',
      icon: path.join(__dirname, 'logo.png')
    })
  }
}

 

2.3config文件夹

1、index.js

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')    //使用nodejs自带的文件路径插件

module.exports = {
  dev: {    //开发环境 ,使用config/dev.env.js中定义的预编译环境

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',   //编译发布上线路径的根目录,可配置为资源服务器域名或cdn域名
    proxyTable: {     //代理接口,可跨域        '/api': {       //将代理请求/api/posts/1 到http://www.mwcxs.top/posts/1                                           target: 'http://jsonplaceholder.typicode.com',                              changeOrigin: true,   //本地会虚拟一个服务端接受你的请求并带你发送请求,这样避免跨域问题                                    pathRewrite: {                                   '^/api': ''                          }               }
    },   

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    // Use Eslint Loader?
    // If true, your code will be linted during bundling and
    // linting errors and warnings will be shown in the console.
    useEslint: true,    //使用esLint检查代码
    // If true, eslint errors and warnings will also be shown in the error overlay
    // in the browser.
    showEslintErrorsInOverlay: false,

    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,    

    cssSourceMap: true    //是否开启cssSourceMap
  },

  build: {     //生产环境  使用config/prod.env.js中定义的编译环境
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),   //编译输出index.html

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),    //输出静态资源根路径
    assetsSubDirectory: 'static',    //输出二级目录
    assetsPublicPath: '/',    //编译发布上线路径的根目录,可配置为资源服务器域名或者CDN域名
  
    /**
     * Source Maps
     */

    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,    //是否开启gzip,默认不开启
    productionGzipExtensions: ['js', 'css'],   //gzip模式下需要压缩的文件的扩展名

    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
}

该文件配置了开发和生产两种环境下的配置。

 

2.4babel配置文件

{
  "presets": [
    ["env", {
      "modules": false,
      "targets": {    //对babel_env或node_env指定不同的环境变量,进行不同的编译操作
        "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
      }
    }],
    "stage-2"
  ],
  "plugins": ["transform-vue-jsx", "transform-runtime"],   //转码用的插件
  "env": {
    "test": {
      "presets": ["env", "stage-2"],
      "plugins": ["transform-vue-jsx", "transform-es2015-modules-commonjs", "dynamic-import-node"]
    }
  }
}

 

2.5编码规范.editorconfig

root = true

[*]     //对所有文件应用下面的规则
charset = utf-8      //编码规范用utf-8
indent_style = space   //缩进用空格
indent_size = 2        //缩进数量为2个空格
end_of_line = lf       //换行符格式
insert_final_newline = true    //是否在文件的最后插入一个空行
trim_trailing_whitespace = true    //是否删除行尾的空格

 

2.6src/main.js文件

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false    //生产环境提示,这里设置成false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'    //引入App组件

 

2.7src/app.vue文件解读

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

<template>标签包裹的内容:这是模板的htmlDom的结构

<script>标签包括的js内容:可以在这里写一些页面的js逻辑代码

<style>标签包裹的css内容:页面需要的css样式

 

2.8src/router/index.js 路由文件

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'

Vue.use(Router)

export default new Router({
  routes: [   //配置路由
    {
      path: '/',   //访问路径
      name: 'HelloWorld',   //路由名称
      component: HelloWorld  //路由需要的组件
    }
  ]
})

vue-router具体可以看官方的文档:http://router.vuejs.org/

 

三、总结

webpack的使用博大精深,仅仅是入门学习。