Vue-cli2项目文件目录解析

前言

不是原创,真的不是原创,主要我是根据CSDN的一篇文章和其余平台上的文章整理而来,在最后我会贴上全部原文的地址,下面正式进入正文。css

Vue-cli项目文件目录结构

这个是Vue-cli2.0版本的文件目录结构,整体来讲就是以下图的
imagehtml

build文件目录

一、build.js文件: 是咱们完成项目以后须要运行的, 能够将咱们的项目文件打包成 静态文件,存放在项目根目录的 dist 文件夹中(如今目录里尚未这个文件夹,npm run build的时候会自动生成),固然你能够本身设置路径,是在 config 文件夹中的 index.js 中改,能够指定主页,默认是 index.html。vue

'use strict' // 调用exports出来的一个函数 require('./check-versions')() // 全局环境变量的设置(默认生产模式) process.env.NODE_ENV = 'production' // ora,一个能够在终端显示spinner的插件,就是日志输出 const ora = require('ora') // rm,用于删除文件或文件夹的插件 const rm = require('rimraf') // path,node中默认处理文件路径的模块 const path = require('path') // chalk,用于在控制台输出带颜色字体的插件 const chalk = require('chalk') const webpack = require('webpack') // config,项目配置文件 const config = require('../config') // 加载生产包的配置 const webpackConfig = require('./webpack.prod.conf') const spinner = ora('building for production...') // 开启loading动画 spinner.start() // 首先将整个dist文件夹以及里面的内容删除,以避免遗留旧的没用的文件 // 删除完成后才开始webpack构建打包 rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { if(err) throw err // 执行webpack构建打包,完成以后在终端输出构建完成的相关信息或者输出报错信息并退出程序 webpack(webpackConfig, (err, stats) => { spinner.stop() if(err) throw err process.stdout.write(stats.toString({ colors: true, modules: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build. children: false, chunks: false, chunkModules: false }) + '\n\n') if(stats.hasErrors()) { 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')) }) })

二、check-version.js文件: 主要是检查一些所依赖的工具的版本是否适用,如nodejs、npm,若版本过低则会提示出来。node

'use strict' // chalk,用于在控制台输出带颜色字体的插件 const chalk = require('chalk') // 引入版本检查工具 const semver = require('semver') const packageConfig = require('../package.json') const shell = require('shelljs') function exec(cmd) { return require('child_process').execSync(cmd).toString().trim() } const versionRequirements = [{ name: 'node', currentVersion: semver.clean(process.version), versionRequirement: packageConfig.engines.node }] if(shell.which('npm')) { versionRequirements.push({ name: 'npm', currentVersion: exec('npm --version'), versionRequirement: packageConfig.engines.npm }) } module.exports = function() { const warnings = [] for(let i = 0; i < versionRequirements.length; i++) { const mod = versionRequirements[i] // 检查版本是否合法 if(!semver.satisfies(mod.currentVersion, mod.versionRequirement)) { warnings.push(mod.name + ': ' + chalk.red(mod.currentVersion) + ' should be ' + chalk.green(mod.versionRequirement)) } } if(warnings.length) { console.log('') console.log(chalk.yellow('To use this template, you must update following to modules:')) console.log() for(let i = 0; i < warnings.length; i++) { const warning = warnings[i] console.log(' ' + warning) } console.log() process.exit(1) } }

三、utils.js文件: 一个功能模块,以便于解析各类格式的css,如 less,sass 什么的。webpack

'use strict' const path = require('path') const config = require('../config') // 这里用来提取css样式 // extract-text-webpack-plugin能够提取bundle中的特定文本,将提取后的文本单独存放到另外的文件 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 : config.dev.assetsSubDirectory return path.posix.join(assetsSubDirectory, _path) } // 生成css、sass、scss等各类用来编写样式的语言所对应的loader配置 exports.cssLoaders = function(options) { options = options || {} // css-loader配置 const cssLoader = { loader: 'css-loader', options: { // 是否使用source-map sourceMap: options.sourceMap } } const postcssLoader = { loader: 'postcss-loader', options: { sourceMap: options.sourceMap } } // generate loader string to be used with extract text plugin // 生成各类loader配置,而且配置了extract-text-pulgin function generateLoaders(loader, loaderOptions) { const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] // 例如generateLoaders('less'),这里就会push一个less-loader // less-loader先将less编译成css,而后再由css-loader去处理css // 其余sass、scss等语言也是同样的过程 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) { // 配置extract-text-plugin提取样式 return ExtractTextPlugin.extract({ use: loaders, fallback: 'vue-style-loader' }) } else { // 无需提取样式则简单使用vue-style-loader配合各类样式loader去处理<style>里面的样式 return ['vue-style-loader'].concat(loaders) } } // https://vue-loader.vuejs.org/en/configurations/extract-css.html // 获得各类不一样处理样式的语言所对应的loader return { 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) // 生成处理单独的.css、.sass、.scss等样式文件的规则 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 = () => { const notifier = require('node-notifier') return(severity, errors) => { if(severity !== 'error') return 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') }) } }

四、vue-loader.conf.js文件: 用来解决各类css文件的,定义了诸如css,less,sass之类的和样式有关的loadergit

'use strict'
const utils = require('./utils')
const config = require('../config')
const isProduction = process.env.NODE_ENV === 'production'
const sourceMapEnabled = isProduction ? config.build.productionSourceMap : config.dev.cssSourceMap
module.exports = {
  loaders: utils.cssLoaders({
    sourceMap: sourceMapEnabled,
    extract: isProduction
  }),
  cssSourceMap: sourceMapEnabled,
  cacheBusting: config.dev.cacheBusting,
  transformToRequire: {
    video: ['src', 'poster'],
    source: 'src',
    img: 'src',
    image: 'xlink:href'
  }
}

五、webpack.base.conf.js文件: webpack基础配置,定义入口文件路径和输出文件路径,以及各类文件转义的规则,是一个核心的配置文件es6

'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 = () => ({ 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, '../'), // webpack的入口文件 entry: { app: './src/main.js' }, // webpack的输出文件 output: { // 指定路径 path: config.build.assetsRoot, // 指定输出名 filename: '[name].js', publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath }, /**  * 当webpack试图去加载模块的时候,它默认是查找以 .js 结尾的文件的,  * 它并不知道 .vue 结尾的文件是什么鬼玩意儿,  * 因此咱们要在配置文件中告诉webpack,  * 遇到 .vue 结尾的也要去加载,  * 添加 resolve 配置项,以下:  */ resolve: { extensions: ['.js', '.vue', '.json'], // 建立别名 alias: { 'vue$': 'vue/dist/vue.esm.js', '@': resolve('src'), } }, // 不一样类型模块的处理规则 就是用不一样的loader处理不一样的文件 module: { rules: [{ // 对全部.vue文件使用vue-loader进行编译 test: /\.vue$/, loader: 'vue-loader', options: vueLoaderConfig }, { // 对src和test文件夹下的.js文件使用babel-loader将es6+的代码转成es5 test: /\.js$/, loader: 'babel-loader', include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')] }, { // 对图片资源文件使用url-loader test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: { // 小于10K的图片转成base64编码的dataURL字符串写到代码中 limit: 10000, // 其余的图片转移到静态资源文件夹 name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, { // 对多媒体资源文件使用url-loader test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, loader: 'url-loader', options: { // 小于10K的资源转成base64编码的dataURL字符串写到代码中 limit: 10000, // 其余的资源转移到静态资源文件夹 name: utils.assetsPath('media/[name].[hash:7].[ext]') } }, { // 对字体资源文件使用url-loader test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, // hash:7 表明 7位数的 hash name: utils.assetsPath('fonts/[name].[hash:7].[ext]') } }] }, node: { // 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.dev.conf.js文件: webpack开发环境配置,构建开发本地服务器github

'use strict' const utils = require('./utils') const webpack = require('webpack') // 基本配置的参数 const config = require('../config') // webpack-merge是一个能够合并数组和对象的插件 const merge = require('webpack-merge') const path = require('path') // webpack基本配置文件(开发和生产环境公用部分 const baseWebpackConfig = require('./webpack.base.conf') const CopyWebpackPlugin = require('copy-webpack-plugin') // html-webpack-plugin用于将webpack编译打包后的产品文件注入到html模板中 // 即在index.html里面加上<link>和<script>标签引用webpack打包后的文件 const HtmlWebpackPlugin = require('html-webpack-plugin') // friendly-errors-webpack-plugin用于更友好地输出webpack的警告、错误等信息 const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') // 自动检索下一个可用端口 const portfinder = require('portfinder') const HOST = process.env.HOST // 读取系统环境变量的port const PORT = process.env.PORT && Number(process.env.PORT) // 合并baseWebpackConfig配置 const devWebpackConfig = merge(baseWebpackConfig, { module: { // 对一些独立的css文件以及它的预处理文件作一个编译 rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) }, // cheap-module-eval-source-map is faster for development devtool: config.dev.devtool, // these devServer options should be customized in /config/index.js // webpack-dev-server服务器配置 devServer: { // console 控制台显示的消息,可能的值有 none, error, warning 或者 info clientLogLevel: 'warning', historyApiFallback: { rewrites: [{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },], }, // 开启热模块加载 hot: true, contentBase: false, // since we use CopyWebpackPlugin. compress: true, // process.env 优先 host: HOST || config.dev.host, // process.env 优先 port: PORT || config.dev.port, open: config.dev.autoOpenBrowser, overlay: config.dev.errorOverlay ? { warnings: false, errors: true } : false, publicPath: config.dev.assetsPublicPath, // 代理设置 proxy: config.dev.proxyTable, quiet: true, // necessary for FriendlyErrorsPlugin // 启用 Watch模式。这意味着在初始构建以后,webpack将继续监放任何已解析文件的更改 watchOptions: { // 经过传递 true开启 polling,或者指定毫秒为单位进行轮询。默认为false poll: config.dev.poll, } }, plugins: [ new webpack.DefinePlugin({ 'process.env': require('../config/dev.env') }), // 模块热替换它容许在运行时更新各类模块,而无需进行彻底刷新 new webpack.HotModuleReplacementPlugin(), // HMR shows correct file names in console on update. new webpack.NamedModulesPlugin(), // 跳过编译时出错的代码并记录下来,主要做用是使编译后运行时的包不出错 new webpack.NoEmitOnErrorsPlugin(), // https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ // 指定编译后生成的html文件名 filename: 'index.html', // 须要处理的模板 template: 'index.html', // 打包过程当中输出的js、css的路径添加到html文件中 // css文件插入到head中 // js文件插入到body中,可能的选项有 true, 'head', 'body', false inject: true }), // 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 // 发布新的端口,对于e2e测试 process.env.PORT = port // add port to devServer config devWebpackConfig.devServer.port = port // 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) } }) })

七、webpack.prod.conf.js文件: webpack生产环境配置web

'use strict' // node内部默认的文件路径处理模块 const path = require('path') const utils = require('./utils') const webpack = require('webpack') const config = require('../config') // 文件配置合并的插件,做用是使生产文件webpack.prod.conf和 // 开发文件webpack.dev.conf文件继承webpack.base.conf文件部分 const merge = require('webpack-merge') const baseWebpackConfig = require('./webpack.base.conf') // copy-webpack-plugin,用于将static中的静态文件复制到产品文件夹dist const CopyWebpackPlugin = require('copy-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') const ExtractTextPlugin = require('extract-text-webpack-plugin') // optimize-css-assets-webpack-plugin,用于优化和最小化css资源 const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') // uglifyJs 混淆js插件 const UglifyJsPlugin = require('uglifyjs-webpack-plugin') const env = require('../config/prod.env') const webpackConfig = merge(baseWebpackConfig, { module: { // 样式文件的处理规则,对css/sass/scss等不一样内容使用相应的styleLoaders // 由utils配置出各类类型的预处理语言所须要使用的loader,例如sass须要使用sass-loader rules: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true, usePostCSS: true }) }, // 一个开发工具,指定文件格式 devtool: config.build.productionSourceMap ? config.build.devtool : false, // webpack输出路径和命名规则 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 }), // 优化压缩JS代码 new UglifyJsPlugin({ uglifyOptions: { compress: { // 不保留警告 warnings: false } }, sourceMap: config.build.productionSourceMap, parallel: true }), // extract css into its own file // 将css提取到单独的文件,插入到HTML文件中,减小请求数 new ExtractTextPlugin({ 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. // 优化、最小化css代码,若是只简单使用extract-text-plugin可能会形成css重复 // 具体缘由能够看npm上面optimize-css-assets-webpack-plugin的介绍 new OptimizeCSSPlugin({ 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 // 将产品文件所有插入到index.html new HtmlWebpackPlugin({ filename: config.build.index, template: 'index.html', inject: true, minify: { // 删除index.html中的注释 removeComments: true, // 删除index.html中的空格 collapseWhitespace: true, // 删除各类html标签属性值的双引号 removeAttributeQuotes: true // more options: // https://github.com/kangax/html-minifier#options-quick-reference }, // necessary to consistently work with multiple chunks via CommonsChunkPlugin // 注入依赖的时候按照依赖前后顺序进行注入,好比,须要先注入vendor.js,再注入app.js chunksSortMode: 'dependency' }), // keep module.id stable when vendor modules does not change new webpack.HashedModuleIdsPlugin(), // enable scope hoisting new webpack.optimize.ModuleConcatenationPlugin(), // split vendor js into its own file // 将全部从node_modules中引入的js提取到vendor.js,即抽取库文件 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 // 从vendor中提取出manifest,缘由如上 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 // 将static文件夹里面的静态资源复制到dist/static new CopyWebpackPlugin([{ from: path.resolve(__dirname, '../static'), to: config.build.assetsSubDirectory, ignore: ['.*'] }]) ] }) // 若是开启了产品gzip压缩,则利用插件将构建后的产品文件进行压缩 if(config.build.productionGzip) { // 一个用于压缩的webpack插件 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, minRatio: 0.8 })) } // 若是启动了report,则经过插件给出webpack构建打包后的产品文件分析报告 if(config.build.bundleAnalyzerReport) { const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin webpackConfig.plugins.push(new BundleAnalyzerPlugin()) } module.exports = webpackConfig

config文件目录

一、dev.env.js 文件: 开发环境变量配置算法

'use strict' const merge = require('webpack-merge') const prodEnv = require('./prod.env') module.exports = merge(prodEnv, { NODE_ENV: '"development"' })

二、index.js 文件: 项目一些配置变量

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: './',
    proxyTable: {},
    // Various Dev Server sett
    // can be overwritten by process.env.HOSTings
    host: 'lo
    // can be overwritten by process.env.PORT, if port is in use, a free one will be determinedcalhost',
    port: 8080,
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
    poll: 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
  },
  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),
    // Paths
    // npm run build文件输出目录以及文件名
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    // 打完包后输出的路径,有用的一个属性,能够把值设置为baidu.com看看
    assetsPublicPath: './',
    /**
     * 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,
    productionGzipExtensions: ['js', 'css'],
    // 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
  }
}

三、prod.env.js文件: 生产环境变量配置

'use strict' module.exports = { NODE_ENV: '"production"' }

src文件目录

这是源码目录,存放了vue全部的组件、vue路由管理、页面入口文件和程序入口文件。这个目录里面包含的东西并不难理解,在这里就不细说了。

static文件目录

这是静态文件存放目录,主要放一些图片和mock的json数据等。也没啥好细说的,并且通常开发都会为了方便起见而把静态文件放在相关的组件里面。

package.json文件

这是项目的配置文件,定义了项目的基本信息以及项目的相关包依赖,npm运行命令等。在这个文件中,scripts里面定义的是一些比较长的命令,用node去执行一段命令,好比npm run dev,其实就是执行

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

这句话的意思是利用webpack-dev-server读取webpack.dev.conf.js信息并启动一个本地服务。

尾声

对于不少require进来的模块不是很理解的话,能够前往这里查看各个模块的含义。

参考资料

Vue-cli项目文件目录解析

一、这多是vue-cli最全的解析了
二、深刻理解Vue-cli搭建项目后的目录结构探秘

 

转载:https://github.com/CruxF/VueNode-Mongo/issues/1

相关文章
相关标签/搜索