使用vue-cli有時會出現一些莫名的問題,清楚項目的結構文件及其意義方便更好的開發和解決問題,介紹以下:css
build/ // 項目構建(webpack)相關代碼 build.js // 生產環境構建代碼 check-versions.js // 檢查node&npm等版本 utils.js // 構建配置公用工具 vue-loader.conf.js // vue加載器 webpack.base.conf.js // webpack基礎環境配置 webpack.dev.conf.js // webpack開發環境配置 webpack.prod.conf.js // webpack生產環境配置 config/ // 項目開發環境配置相關代碼 dev.env.js // 開發環境變量(看詞明意) index.js //項目一些配置變量 prod.env.js // 生產環境變量 test.env.js // 測試環境變量 dist/ //npm run build打包後生成的文件夾 node_modules/ ... // 項目依賴的模塊 src/ // 源碼目錄 assets/ // 資源目錄 logo.png components/ // vue公共組件 Head.vue Footer.vue pages (或views)/ //視圖 login/ Index.vue list/ Foods.vue router/ // 前端路由 index.js// 路由配置文件 store/ // vuex的狀態管理 App.vue// 頁面入口文件(根組件) main.js// 程序入口文件(入口js文件) static // 靜態文件,好比一些圖片,json數據等 .gitkeep //這個裏面的gitkeep是這個目錄爲空,也能夠把這個目錄提交的git倉庫裏面,由於一般一個空目錄是不能提交git倉庫裏面的 .babelrc// ES6語法編譯配置 .editorconfig// 定義代碼格式 .gitignore// git上傳須要忽略的文件格式 index.html// 入口頁面 package.json// 項目基本信息 README.md// 項目說明
require('./check-versions')() // 檢查 Node 和 npm 版本 process.env.NODE_ENV = 'production' const ora = require('ora') // 一個很好看的 loading 插件 const rm = require('rimraf') const path = require('path') const chalk = require('chalk') const webpack = require('webpack') const config = require('../config') // 加載 config.js const webpackConfig = require('./webpack.prod.conf') // 加載 webpack.prod.conf const spinner = ora('building for production...') spinner.start() // 開始 loading 動畫 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, 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()) { 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' )) }) })
const utils = require('./utils') // 使用一些小工具 const webpack = require('webpack') // 使用 webpack const config = require('../config') // 使用 config/index.js const merge = require('webpack-merge') // 使用 webpack 配置合併插件 const path = require('path') const baseWebpackConfig = require('./webpack.base.conf') // 加載 webpack.base.conf const CopyWebpackPlugin = require('copy-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') // 使用 html-webpack-plugin 插件,這個插件能夠幫咱們自動生成 html 而且注入到 .html 文件中 const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') const portfinder = require('portfinder') const HOST = process.env.HOST const PORT = process.env.PORT && Number(process.env.PORT) // 將咱們 webpack.dev.conf.js 的配置和 webpack.base.conf.js 的配置合併 const devWebpackConfig = merge(baseWebpackConfig, { module: { // 使用 styleLoaders 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 devServer: { clientLogLevel: 'warning', 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, 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 watchOptions: { poll: config.dev.poll, } }, plugins: [ // definePlugin 接收字符串插入到代碼當中, 因此你須要的話能夠寫上 JS 的字符串 new webpack.DefinePlugin({ 'process.env': require('../config/dev.env') }), // HotModule 插件在頁面進行變動的時候只會重回對應的頁面模塊,不會重繪整個 html 文件 new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update. // 使用了 NoErrorsPlugin 後頁面中的報錯不會阻塞,可是會在編譯結束後報錯 new webpack.NoEmitOnErrorsPlugin(), // https://github.com/ampedandwired/html-webpack-plugin // 將 index.html 做爲入口,注入 html 代碼後生成 index.html文件 new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', 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 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) } }) })
const path = require('path') // 使用 NodeJS 自帶的文件路徑插件 const utils = require('./utils') // 引入一些小工具 var webpack = require('webpack') const config = require('../config') const vueLoaderConfig = require('./vue-loader.conf') // 獲取絕對路徑 function resolve (dir) { return path.join(__dirname, '..', dir) } module.exports = { context: path.resolve(__dirname, '../'), 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 }, resolve: { // 自動補全的擴展名 extensions: ['.js', '.vue', '.json'], // 別名,方便引用模塊,例若有了別名以後, // import Vue from 'vue/dist/vue.esm.js'能夠寫成 import Vue from 'vue' alias: { 'vue$': 'vue/dist/vue.esm.js', '@': resolve('src'), } }, // 不一樣類型模塊的處理規則 module: { rules: [ ... // 須要處理的文件及使用的 loader { test: /\.scss$/, loaders: ["style", "css", "sass"] } ] }, plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery" }) ], 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' } }
// Template version: 1.3.1 // see http://vuejs-templates.github.io/webpack for documentation. const path = require('path') module.exports = { // 開發過程當中使用的配置 dev: { // Paths // 編譯輸出的二級目錄 assetsSubDirectory: 'static', // 編譯發佈上線路徑的根目錄,可配置爲資源服務器域名或 CDN 域名 assetsPublicPath: '/', // 須要 proxyTable 代理的接口(可跨域) proxyTable: {}, // 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- /** * Source Maps */ // https://webpack.js.org/configuration/devtool/#development devtool: 'cheap-module-eval-source-map', //可改變爲devtool: '#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 // html入口文件 index: path.resolve(__dirname, '../dist/index.html'), // Paths // 編譯輸出的靜態資源根路徑 assetsRoot: path.resolve(__dirname, '../dist'), // 編譯輸出的二級目錄 assetsSubDirectory: 'static', // 編譯發佈上線路徑的根目錄,可配置爲資源服務器域名或 CDN 域名 assetsPublicPath: './', /** * Source Maps */ // 是否開啓 cssSourceMap 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 // 是否開啓 gzip productionGzip: false, // 須要使用 gzip 壓縮的文件擴展名 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 } }
const path = require('path') const utils = require('./utils') // 使用一些小工具 const webpack = require('webpack') const config = require('../config') // 加載 confi.index.js const merge = require('webpack-merge') // 加載 webpack 配置合併工具 const baseWebpackConfig = require('./webpack.base.conf') // 加載 webpack.base.conf.js const CopyWebpackPlugin = require('copy-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') // 一個能夠插入 html 而且建立新的 .html 文件的插件 const ExtractTextPlugin = require('extract-text-webpack-plugin') // 一個 webpack 擴展,能夠提取一些代碼而且將它們和文件分離開,若是咱們想將 webpack 打包成一個文件 css js 分離開,那咱們須要這個插件 const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') const UglifyJsPlugin = require('uglifyjs-webpack-plugin') const env = require('../config/prod.env') // 合併 webpack.base.conf.js const webpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true, usePostCSS: true }) }, // 是否使用 #source-map 開發工具 devtool: config.build.productionSourceMap ? config.build.devtool : false, output: { // 編譯輸出目錄 path: config.build.assetsRoot, // 編譯輸出文件名 // 咱們能夠在 hash 後加 :6 決定使用幾位 hash 值 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 // definePlugin 接收字符串插入到代碼當中, 因此你須要的話能夠寫上 JS 的字符串 new webpack.DefinePlugin({ 'process.env': env }), new UglifyJsPlugin({ // 壓縮 js (一樣能夠壓縮 css) uglifyOptions: { compress: { warnings: false } }, sourceMap: config.build.productionSourceMap, parallel: true }), // extract css into its own file // 將 css 文件分離出來 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. 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 new HtmlWebpackPlugin({ // 輸入輸出的 .html 文件 filename: 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' }), // 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 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: ['.*'] } ]) ] }) // 開啓 gzip 的狀況下使用下方的配置 if (config.build.productionGzip) { // 加載 compression-webpack-plugin 插件 const CompressionWebpackPlugin = require('compression-webpack-plugin') webpackConfig.plugins.push( // 使用 compression-webpack-plugin 插件進行壓縮 new CompressionWebpackPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: new RegExp( '\\.(' + config.build.productionGzipExtensions.join('|') + ')$' ), threshold: 10240, minRatio: 0.8 }) ) } if (config.build.bundleAnalyzerReport) { const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin webpackConfig.plugins.push(new BundleAnalyzerPlugin()) } module.exports = webpackConfig
{ "presets": [ ["env", { "modules": false, "targets": { "browsers": ["> 1%", "last 2 versions", "not ie <= 8"] } }], "stage-2" ], "plugins": ["transform-vue-jsx", "transform-runtime"] }
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 // 是否刪除行尾的空格
以上是通過收集跟總結的部分,還有許多須要完善,請注意版本,本身嘗試合適的纔是好的。紙上得來終覺淺,絕知此事要躬行!html
完善中……前端