Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Vue-cli directory structure is explained in detail

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains the "vue-cli directory structure detailed explanation", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "vue-cli directory structure detailed explanation" bar!

The project structure of a vue-cli is as follows:

Catalogue

Structure preview

├─ build / / saves some initialization configuration of webpack, project builds │ ├─ build.js / / production environment builds │ ├─ check-version.js / / check npm, node version │ ├─ vue-loader.conf.js / / webpack loader configuration │ ├─ webpack.base.conf.js// webpack basic configuration │ ├─ webpack.dev.conf.js / / development environment configuration Build the configuration of the local development server │ ├─ webpack.prod.conf.js// production environment │├─ config / / config folder saves some project initialization configuration │ ├─ dev.env.js / / development environment configuration │ ├─ index.js / / some project configuration variables │ ├─ prod.env.js / / configuration │ of the production environment ├─ dist / / packaged project ├─ node_modules / / dependency package │├─ src / / Source code directory │ ├─ assets / / static file directory │ ├─ components / / component file │ ├─ router / / routing │ ├─ App.vue / / is the project entry file │ ├─ main.js / / is the core file of the project The configuration file ├─ .editorconfig / / code specification configuration file ├─ .gitignore / / git of the entry ├─ static / / static resource directory ├─ .babelrc / / git ignores the configuration file ├─ .postcssrc.js / / postcss plug-in configuration file ├─ index.html / / page entry file ├─ package-lock.json / / project package control file ├ ─ package.json / / Project configuration └─ README.md / / Project description

Structural analysis

Build

Dev-server.js

First, let's take a look at the build/dev-server.js file that is executed first when "npm run dev" is executed. The document mainly accomplishes the following things:

Check the versions of node and npm, introduce relevant plug-ins and configurations

Webpack compiles and packages the source code and returns the compiler object

Create an express server

Configure development middleware (webpack-dev-middleware) and + hot and heavy load middleware (webpack-hot-middleware)

Mount agent services and middleware

Configure static resources

Start the server to listen on a specific port (8080)

Automatically opens the browser and opens a specific URL (localhost:8080)

Description: the express server provides static file services, but it also uses http-proxy-middleware, a middleware for http request agents. If you need to use the background API in the front-end development process, you can configure proxyTable to proxy the corresponding background requests to a dedicated API server.

/ / check the version of NodeJS and npm require ('. / check-versions') () / / get the basic configuration var config = require ('.. / config') / / if the current environment (NODE_ENV) is not set in the environment variable of Node Then use the dev environment configuration in config as the current environment if (! process.env.NODE_ENV) {process.env.NODE_ENV = JSON.parse (config.dev.env.NODE_ENV)} / / opn is a plug-in that can call the default software to open URLs, pictures, files, etc. / here it is used to call the default browser to open the port for dev-server listening For example: localhost:8080var opn = require ('opn') var path = require (' path') var express = require ('express') var webpack = require (' webpack') / / http-proxy-middleware is an express middleware used to proxy http requests to other servers / example: localhost:8080/api/xxx-- > localhost:3000/api/xxx// this plug-in can be used to proxy requests involved in front-end development to back-end servers that provide services It is convenient to interface with the server with var proxyMiddleware = require ('http-proxy-middleware') / / the webpack configuration in the development environment var webpackConfig = require ('. / webpack.dev.conf') / / dev-server listens to the port. If the port number is not passed in the command line, the port set by config.dev.port is used, for example, 8080var port = process.env.PORT | | config.dev.port// is used to determine whether to automatically open the Boolean variable of the browser. When automatic browser opening is not set in the configuration file, the value is falsevar autoOpenBrowser =!! config.dev.autoOpenBrowser// HTTP proxy table, specify the rule Proxy some API requests to the corresponding server var proxyTable = config.dev.proxyTable// create an express server var app = express () / / webpack start compiling and packaging the source code according to the configuration and return the compiler object var compiler = webpack (webpackConfig) / / webpack-dev-middleware the product files obtained after webpack compilation and packaging are stored in memory but not written to disk / / after the middleware is hung on express for use For these compiled product file services var devMiddleware = require ('webpack-dev-middleware') (compiler {publicPath: webpackConfig.output.publicPath, / / set the access path to the corresponding path in output in webpack configuration: quiet: true / / set to true The middleware var hotMiddleware = require ('webpack-hot-middleware') (compiler, {log: false, / / closes the console's log output heartbeat: 2000 / / the frequency of sending heartbeats}) / / webpack (re) compiles and packages the js, css and other files to the html file after it is compiled and packaged. Force page refresh compiler.plugin ('compilation', function (compilation) {compilation.plugin (' html-webpack-plugin-after-emit', function (data)) via hot reload middleware Cb) {hotMiddleware.publish ({action: 'reload'}) cb ()}) / / set the http proxy rule Object.keys (proxyTable) .forEach (function (context) {var options = proxyTable [context] / / format options) of the express server according to the proxy request configuration in express For example, change 'www.example.com' to {target:' www.example.com'} if (typeof options = 'string') {options = {target: options}} app.use (proxyMiddleware (options.filter | | context, options))}) / / handle fallback for HTML5 history API// redirects a URL that does not exist Used to support SPA (single-page applications) / / for example, using vue-router and enabling history mode app.use (require ('connect-history-api-fallback') ()) / / serve webpack bundle output// mounts webpack-dev-middleware middleware Provide webpack compiled and packaged product file service app.use (devMiddleware) / / enable hot-reload and state-preserving// compilation error display// mount hot reload middleware app.use (hotMiddleware) / / serve pure static assets// provide static file service var staticPath = path.posix.join (config.dev.assetsPublicPath, config.dev.assetsSubDirectory) app.use (staticPath) on the static folder Express.static ('. / static') / / visit the link var uri = 'http://localhost:' + port// to create promise After the application service starts, resolve// facilitates the external file to require the code after the dev-server is written var _ resolvevar readyPromise = new Promise (resolve = > {_ resolve = resolve}) console.log ('> Starting dev server...') / / webpack-dev-middleware waits for webpack to complete all compilation and packaging, and then outputs the prompt to the console. Indicates that the service is officially started / / the service is officially launched before automatically opening the browser entry page devMiddleware.waitUntilValid (() = > {console.log ('> Listening at'+ uri +'\ n') / / when env is testing Don't need open it if (autoOpenBrowser & & process.env.NODE_ENV! = = 'testing') {opn (uri)} _ resolve ()) / / start the express server and listen on the corresponding port var server = app.listen (port) / / expose the functions of this module for external use For example, the following usage / / var devServer = require ('. / build/dev-server') / / devServer.ready.then (() = > {...}) / / if (...) {devServer.close ()} module.exports = {ready: readyPromise, close: () = > {server.close ()}}

Webpack.base.conf.js

As you can see from the code, the webpack configuration used by dev-server comes from the build/webpack.dev.conf.js file (build/webpack.prod.conf.js is used in the test environment, which is not considered here for the time being). And webpack.base.conf.js is referenced in build/webpack.dev.conf.js, so I'll analyze webpack.base.conf.js first.

Webpack.base.conf.js mainly accomplishes the following things:

Configure the webpack compilation entry

Configure webpack output paths and naming rules

Configure module resolve rules

Configure processing rules for different types of modules

Description: this configuration is only configured with .js, .vue, pictures, fonts and other file processing rules, if you need to deal with other files can be configured separately in module.rules.

Var path = require ('path') var fs = require (' fs') var utils = require ('. / utils') var config = require ('.. / config') var vueLoaderConfig = require ('. / vue-loader.conf') / / get the absolute path function resolve (dir) {return path.join (_ dirname,'., dir)} module.exports = {/ / webpack entry file entry: {app:'. / src/main.js'} / / webpack output path and naming convention output: {/ / destination folder path of webpack output (e.g. / dist) path: config.build.assetsRoot, / / webpack output bundle file naming format filename:'[name] .js', / / release path of webpack compilation output (e.g.'/ / cdn.xxx.com/app/') publicPath: process.env.NODE_ENV = = 'production'? Config.build.assetsPublicPath: config.dev.assetsPublicPath}, / / Rule resolve of module resolve: {extensions: ['.js', '.vue', '.json'], / / alias to facilitate referencing modules, for example, after aliases exist / / import Vue from 'vue/dist/vue.common.js' can be written as import Vue from' vue' alias: {'vue$':' vue/dist/vue.esm.js','@': resolve ('src'),}, symlinks: false} / / processing rules for different types of modules module: {rules: [{/ / A pair of .js and .vue files under src and test folders use eslint-loader for code specification checking test: /\. (js | vue) $/, loader: 'eslint-loader', enforce:' pre', include: [resolve ('src'), resolve (' test')] Options: {formatter: require ('eslint-friendly-formatter')}}, {/ / a pair of .vue files compiled with vue-loader test: /\ .vue $/, loader:' vue-loader', options: vueLoaderConfig}, {/ / a pair of .js files under the src and test folders use babel-loader to convert es6+ code to es5 test: /\ .js $/, loader: 'babel-loader' Include: [resolve ('src'), resolve (' test')]}, {/ / A pair of image resource files use url-loader test: /\. (png | jpe?g | gif | svg) (\?. *)? $/, loader: 'url-loader', options: {/ / images less than 10K are converted into base64-encoded dataURL strings and written to the code limit: 10000 / / transfer other images to the static resource folder name: utils.assetsPath ('img/ [name]. [hash: 7]. [ext]')}, {/ / a pair of multimedia resource files use url-loader test: /\. (mp4 | webm | ogg | wav | flac | aac) (\?. *)? $/, loader: 'url-loader' Options: {/ / Resources less than 10K are converted into base64-encoded dataURL strings written in the code limit: 10000, / / other resources are transferred to the static resource folder name: utils.assetsPath ('media/ [name]. [hash: 7]. [ext]')}} {/ / A pair of font resource files use url-loader test: /\. (woff2? | eot | ttf | otf) (\?. *)? $/, loader: 'url-loader', options: {/ / Resources less than 10K are converted into base64-encoded dataURL strings and written to the code limit: 10000 / / transfer other resources to the static resource folder name: utils.assetsPath ('fonts/ [name]. [hash: 7]. [ext]')}

Webpack.dev.conf.js

Next, let's take a look at webpack.dev.conf.js, which adds and improves the configuration of the development environment on the basis of webpack.base.conf, including the following things:

Add the hot reload client code of webpack to the corresponding application of each entry

Merge basic webpack configuration

Configure the processing rules for style files, styleLoaders

Configure Source Maps

Configure the webpack plug-in

Var utils = require ('. / utils') var webpack = require ('webpack') var config = require ('.. / config') / / webpack-merge is a plug-in that merges arrays and objects var merge = require ('webpack-merge') var baseWebpackConfig = require ('. / webpack.base.conf') / / html-webpack-plugin is used to inject webpack compiled and packaged product files into the html template / / that is to add automatically to index.html And tags refer to the webpack packaged file var HtmlWebpackPlugin = require ('html-webpack-plugin') / / friendly-errors-webpack-plugin for more friendly output of webpack warnings, Error and other information var FriendlyErrorsPlugin = require ('friendly-errors-webpack-plugin') / / add hot-reload related code to entry chunks// add dev-client to each entry page (application) Hot update Object.keys (baseWebpackConfig.entry) .forEach (function (name) {baseWebpackConfig.entry [name] = ['. / build/dev-client'] .concat (baseWebpackConfig.entry [name])}) module.exports = merge (baseWebpackConfig, {module: {/ / style file processing rules) for communication with hot and overloaded plug-ins of dev-server Use the corresponding styleLoaders / / for different contents such as css/sass/scss / / the loader required to configure various types of preprocessing languages by utils For example, sass needs to use sass-loader rules: utils.styleLoaders ({sourceMap: config.dev.cssSourceMap})}, / / cheap-module-eval-source-map is faster for development / / use this source-map faster devtool:'# cheap-module-eval-source-map', / / webpack plug-in plugins: [new webpack.DefinePlugin ({'process.env': config.dev.env}), / / enable webpack hot update function new webpack.HotModuleReplacementPlugin () / / skip the error reporting phase when there is an error in the compilation of webpack Compilation is not blocked, new webpack.NoEmitOnErrorsPlugin () is reported at the end of compilation, / / dependency is automatically injected into the html template, and the final html file is output to the target folder new HtmlWebpackPlugin ({filename: 'index.html', template:' index.html', inject: true}), new FriendlyErrorsPlugin ()]})

Utils

This configuration file is the wepack-related configuration file for the vue development environment, and is mainly used to deal with css-loader and vue-style-loader

/ / introduce the nodejs path module var path = require ('path') / / introduce the index.js configuration file var config = require ('.. / config') / / in the config directory to extract the css into a separate css file / / see (1) var ExtractTextPlugin = require ('extract-text-webpack-plugin') / / exports is actually an object, and module.exports is ultimately used to export the method. Export assetsPathexports.assetsPath = function (_ path) {/ / if it is a production environment, assetsSubDirectory is' static', otherwise or 'static', var assetsSubDirectory = process.env.NODE_ENV = =' production'? Config.build.assetsSubDirectory: the difference between config.dev.assetsSubDirectory / / path.join and path.posix.join is that the former returns the full path, while the latter returns the relative root path of the full path / / that is, the path of path.join is C:a/a/b/xiangmu/b So path.posix.join is b return path.posix.join (assetsSubDirectory, _ path) / / so the function of this method is to return a clean relative root path} / / below is the relevant configuration of the export cssLoaders exports.cssLoaders = function (options) {/ / options is the empty object options = options if there is no value | {} / / basic configuration of cssLoader var cssLoader = {loader: 'css-loader' Options: {/ / options is used to pass parameters to loader / / minimize indicates compression If it is a production environment, compress the css code minimize: process.env.NODE_ENV = = 'production', / / whether to enable cssmap. The default is false sourceMap: options.sourceMap}} / / generate loader string to be used with extract text plugin function generateLoaders (loader, loaderOptions) {/ / put the above basic cssLoader configuration in an array var loaders = [cssLoader] / / add it to the loaders array if the function passes a separate loader This loader may be an if (loader) such as less,sass {loaders.push ({/ / load the corresponding loader loader: loader +'- loader', / / Object.assign is the method of es6, which is mainly used to merge objects Shallow copy options: Object.assign ({}, loaderOptions, {sourceMap: options.sourceMap})} / / Extract CSS when that option is specified / / (which is the case during production build) / / Note this extract is a custom attribute, which can be defined in options. The main function is to extract files separately when configured as true, and false means that files are not extracted separately. This can be configured separately when in use. I immediately felt that the author of vue was so powerful that if (options.extract) {return ExtractTextPlugin.extract ({use: loaders, fallback: 'vue-style-loader'})} else {return [' vue-style-loader'] .concat (loaders)} / / the above code is used to return the final read and import loader. To deal with files of corresponding types} / / https://vue-loader.vuejs.org/en/configurations/extract-css.html return {css: generateLoaders (), / / css corresponds to vue-style-loader and css-loader postcss: generateLoaders (), / / postcss corresponds to vue-style-loader and css-loader less: generateLoaders ('less'), / / less corresponds to vue-style-loader and less-loader sass: generateLoaders (' sass', {indentedSyntax: true}) / / sass corresponds to vue-style-loader and sass-loader scss: generateLoaders ('sass'), / / scss corresponds to vue-style-loader and sass-loader stylus: generateLoaders (' stylus'), / / stylus corresponds to vue-style-loader and stylus-loader styl: generateLoaders ('stylus') / / styl corresponds to vue-style-loader and styl-loader}} / / Generate loaders for standalone style files (outside of. Vue) / / the following mainly deals with the packaging of file types imported by import The exports.cssLoaders above is exports.styleLoaders = function (options) {var output = [] / / below is the loader object var loaders = exports.cssLoaders (options) for (var extension in loaders) of various css files generated. {/ / extract the laoder of each document var loader = loaders [extension] output.push ({/ / push the final result into the output array Test: new RegExp ('\\.'+ extension +'$'), use: loader})} return output}

The extract-text-webpack-plugin plug-in is used to extract text from bundle into a separate file

Const ExtractTextPlugin = require ("extract-text-webpack-plugin") Module.exports = {module: {rules: [{test: /\ .css $/, / / is mainly used to process css files use: ExtractTextPlugin.extract ({fallback: "style-loader", / / fallback means to import use using style-loader if the css file is not successfully imported: "css-loader" / / means to use css-loader to read css files from js})}]] Plugins: [new ExtractTextPlugin ("styles.css") / / means to generate a styles.css file]}}

Vue-loader.conf.js

Var utils = require ('. / utils') var config = require ('.. / config') var isProduction = process.env.NODE_ENV = = 'production'module.exports = {/ / handle styles in the .vue file loaders: utils.cssLoaders ({/ / do you want to open source-map sourceMap: isProduction? Config.build.productionSourceMap: config.dev.cssSourceMap, / / whether to extract styles to a separate file extract: isProduction}), transformToRequire: {video: 'src', source:' src', img: 'src', image:' xlink:href'}}

Dev-client.js

Dev-client.js is mainly written in the browser-side code, used to achieve hot updates of webpack.

/ * eslint-disable * / / implement browser-side EventSource for two-way communication with server / / two-way communication between webpack hot overload client and hot overload plug-in on dev-server / / server webpack will push messages to the client after recompiling Tell the client to update require ('eventsource-polyfill') / / webpack hot overload client var hotClient = require (' webpack-hot-middleware/client?noInfo=true&reload=true') / / the client receives the update action, and performs a page refresh hotClient.subscribe (function (event) {if (event.action = 'reload') {_ window.location.reload ()}})

Build.js

When executing "npm run build", the first thing to execute is the build/build.js file, and build.js mainly accomplishes the following things:

Loading animation

Delete destination folder

Perform webpack build

Output information

Note: webpack is compiled and output to the target folder specified in the configuration; the target folder is deleted and then created to remove the old content to avoid unpredictable effects.

/ / check the version of NodeJS and npm require ('. / check-versions') () process.env.NODE_ENV = 'production'// ora, a plug-in that can display spinner on the terminal var ora = require (' ora') / / rm, and a plug-in used to delete files or folders var rm = require ('rimraf') var path = require (' path') / / chalk Plug-in var chalk = require ('chalk') var webpack = require (' webpack') var config = require ('.. / config') var webpackConfig = require ('. / webpack.prod.conf') var spinner = ora ('building for production...') spinner.start () / enable loading animation / / first delete the entire dist folder and its contents Avoid legacy useless files / / start webpack build packaging rm (path.join (config.build.assetsRoot, config.build.assetsSubDirectory), err = > {if (err) throw err / / execute webpack build packaging after deletion is completed After completion, output the relevant information of the completed construction or output the error message at the terminal and exit the program webpack (webpackConfig, function (err, stats) {spinner.stop () if (err) throw err process.stdout.write (stats.toString ({colors: true, modules: false, 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')})})

Webpack.prod.conf.js

The webpack configuration used in the build comes from webpack.prod.conf.js, which is also a further improvement on the basis of webpack.base.conf. The main tasks are as follows:

Merge basic webpack configuration

Configure the processing rules for style files, styleLoaders

Configure the output of webpack

Configure the webpack plug-in

Webpack plug-in configuration in gzip mode

Webpack-bundle analysis

Description: there are many plug-ins such as vilifying compression code and extracting css files in the webpack plug-in.

Var path = require ('path') var utils = require ('. / utils') var webpack = require ('webpack') var config = require ('.. / config') var merge = require ('webpack-merge') var baseWebpackConfig = require ('. / webpack.base.conf') / / copy-webpack-plugin Used to copy static files in static to the product folder distvar CopyWebpackPlugin = require ('copy-webpack-plugin') var HtmlWebpackPlugin = require (' html-webpack-plugin') var ExtractTextPlugin = require ('extract-text-webpack-plugin') / / optimize-css-assets-webpack-plugin Used to optimize and minimize css resources var OptimizeCSSPlugin = require ('optimize-css-assets-webpack-plugin') var env = config.build.envvar webpackConfig = merge (baseWebpackConfig, {module: {/ / processing rules for style files, using corresponding styleLoaders / / for different content such as css/sass/scss / / loader for configuring various types of preprocessing languages by utils For example, sass needs to use sass-loader rules: utils.styleLoaders ({sourceMap: config.build.productionSourceMap, extract: true})}, / / whether to use source-map devtool: config.build.productionSourceMap?'# source-map': false, / / webpack output path and naming convention output: {path: config.build.assetsRoot, filename: utils.assetsPath ('js/ [name]. [chunkhash] .js') ChunkFilename: utils.assetsPath ('js/ [id]. [chunkhash] .js')}, / / webpack plug-in plugins: [/ / http://vuejs.github.io/vue-loader/en/workflow/production.html new webpack.DefinePlugin ({'process.env': env}), / / vilify compressed JS code new webpack.optimize.UglifyJsPlugin ({compress: {warnings: false}, sourceMap: true}) / / extract css into its own file / / extract css to a separate file new ExtractTextPlugin ({filename: utils.assetsPath ('css/ [name]. [contenthash] .css')), / / Compress extracted CSS. We are using this plugin so that possible / / duplicated CSS from different components can be deduped. / / optimize and minimize css code. If you simply use extract-text-plugin, it may cause css duplication / / for specific reasons, please see the introduction of optimize-css-assets-webpack-plugin on npm: new OptimizeCSSPlugin ({cssProcessorOptions: {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 / / inject references from the product file into index.html new HtmlWebpackPlugin ({filename: config.build.index, template: 'index.html', inject: true, minify: {/ / remove comments removeComments: true in index.html, / / delete spaces in index.html collapseWhitespace: true / / remove the double quotation marks of various html tag attribute values removeAttributeQuotes: true / / more options: / / https://github.com/kangax/html-minifier#options-quick-reference}, / / necessary to consistently work with multiple chunks via CommonsChunkPlugin / / inject dependencies according to the dependency sequence For example, you need to inject vendor.js first, and then app.js chunksSortMode: 'dependency'}), / / keep module.id stable when vender modules does not change new webpack.HashedModuleIdsPlugin (), / / split vendor js into its own file / / to extract all js introduced from node_modules to vendor.js That is, extract the library file new webpack.optimize.CommonsChunkPlugin ({name: 'vendor', minChunks: function (module, count) {/ / 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 / / extract manifest from vendor For reasons such as new webpack.optimize.CommonsChunkPlugin ({name: 'manifest', chunks: [' vendor']}), / / copy custom static assets / / copy the static resources in the static folder to dist/static new CopyWebpackPlugin ([{from: path.resolve (_ _ dirname,'.. / static'), to: config.build.assetsSubDirectory) Ignore: ['. *']})]}) / / if product gzip compression is enabled Then use the plug-in to compress the built product file if (config.build.productionGzip) {/ / A webpack plug-in for compression var CompressionWebpackPlugin = require ('compression-webpack-plugin') webpackConfig.plugins.push (new CompressionWebpackPlugin ({asset:' [path] .gz [query]', / / compression algorithm algorithm: 'gzip' Test: new RegExp ('\\. ('+ config.build.productionGzipExtensions.join ('|) +') $'), threshold: 10240, minRatio: 0.8})} / / if report is started The analysis report of the packaged product file if (config.build.bundleAnalyzerReport) {var BundleAnalyzerPlugin = require ('webpack-bundle-analyzer'). BundleAnalyzerPlugin webpackConfig.plugins.push (new BundleAnalyzerPlugin ())} module.exports = webpackConfig is given through the plug-in.

Check-versions.js

/ / chalk, which is used to output plug-ins with colored fonts var chalk = require ('chalk') / / semver in the console, and semantic version checking plug-ins (The semantic version parser used by npm) var semver = require (' semver') var packageConfig = require ('.. / package.json') / / shelljs The plug-in that executes the Unix command line var shell = require ('shelljs') / / the child process executes the instruction cmd and returns the result function exec (cmd) {return require (' child_process') .execSync (cmd). ToString (). Trim ()} / / node and npm version requirements var 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 () {var warnings = [] / / determine whether the version meets the requirements for (var I = 0) I

< versionRequirements.length; i++) { var 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 (var i = 0; i < warnings.length; i++) { var warning = warnings[i] console.log(' ' + warning) } console.log() process.exit(1) }} config index.js config文件夹下最主要的文件就是index.js了,在这里面描述了开发和构建两种环境下的配置,前面的build文件夹下也有不少文件引用了index.js里面的配置 // see http://vuejs-templates.github.io/webpack for documentation.var path = require('path')module.exports = { // 构建产品时使用的配置 build: { // 环境变量 env: require('./prod.env'), // html入口文件 index: path.resolve(__dirname, '../dist/index.html'), // 产品文件的存放路径 assetsRoot: path.resolve(__dirname, '../dist'), // 二级目录,存放静态资源文件的目录,位于dist文件夹下 assetsSubDirectory: 'static', // 发布路径,如果构建后的产品文件有用于发布CDN或者放到其他域名的服务器,可以在这里进行设置 // 设置之后构建的产品文件在注入到index.html中的时候就会带上这里的发布路径 assetsPublicPath: '/', // 是否使用source-map productionSourceMap: true, // 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模式下需要压缩的文件的扩展名,设置js、css之后就只会对js和css文件进行压缩 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 // 是否展示webpack构建打包之后的分析报告 bundleAnalyzerReport: process.env.npm_config_report }, // 开发过程中使用的配置 dev: { // 环境变量 env: require('./dev.env'), // dev-server监听的端口 port: 8080, // 是否自动打开浏览器 autoOpenBrowser: true, // 静态资源文件夹 assetsSubDirectory: 'static', // 发布路径 assetsPublicPath: '/', // 代理配置表,在这里可以配置特定的请求代理到对应的API接口 // 例如将'localhost:8080/api/xxx'代理到'www.example.com/api/xxx' proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. // 是否开启 cssSourceMap cssSourceMap: false }}'use strict'const path = require('path')module.exports = { dev: { // 开发环境下面的配置 assetsSubDirectory: 'static',//子目录,一般存放css,js,image等文件 assetsPublicPath: '/',//根目录 proxyTable: {},//可利用该属性解决跨域的问题 host: 'localhost', // 地址 port: 8080, //端口号设置,端口号占用出现问题可在此处修改 autoOpenBrowser: false,//是否在编译(输入命令行npm run dev)后打开http://localhost:8080/页面,以前配置为true,近些版本改为false,个人偏向习惯自动打开页面 errorOverlay: true,//浏览器错误提示 notifyOnErrors: true,//跨平台错误提示 poll: false, //使用文件系统(file system)获取文件改动的通知devServer.watchOptions devtool: 'cheap-module-eval-source-map',//增加调试,该属性为原始源代码(仅限行)不可在生产环境中使用 cacheBusting: true,//使缓存失效 cssSourceMap: true//代码压缩后进行调bug定位将非常困难,于是引入sourcemap记录压缩前后的位置信息记录,当产生错误时直接定位到未压缩前的位置,将大大的方便我们调试 }, build: { // 生产环境下面的配置 index: path.resolve(__dirname, '../dist/index.html'),//index编译后生成的位置和名字,根据需要改变后缀,比如index.php assetsRoot: path.resolve(__dirname, '../dist'),//编译后存放生成环境代码的位置 assetsSubDirectory: 'static',//js,css,images存放文件夹名 assetsPublicPath: '/',//发布的根目录,通常本地打包dist后打开文件会报错,此处修改为./。如果是上线的文件,可根据文件存放位置进行更改路径 productionSourceMap: true, devtool: '#source-map',//① //unit的gzip命令用来压缩文件,gzip模式下需要压缩的文件的扩展名有js和css productionGzip: false, productionGzipExtensions: ['js', 'css'], bundleAnalyzerReport: process.env.npm_config_report }} prod.env.js 当开发是调取dev.env.js的开发环境配置,发布时调用prod.env.js的生产环境配置 'use strict'module.exports = { NODE_ENV: '"production"'} dev.env.js config内的文件其实是服务于build的,大部分是定义一个变量export出去。 'use strict'//采用严格模式const merge = require('webpack-merge')//①const prodEnv = require('./prod.env')//webpack-merge提供了一个合并函数,它将数组和合并对象创建一个新对象。//如果遇到函数,它将执行它们,通过算法运行结果,然后再次将返回的值封装在函数中.这边将dev和prod进行合并module.exports = merge(prodEnv, { NODE_ENV: '"development"'}) src ①、assets文件:脚手架自动会放入一个图片在里面作为初始页面的logo。平常我们使用的时候会在里面建立js,css,img,fonts等文件夹,作为静态资源调用 ②、components文件夹:用来存放组件,合理地使用组件可以高效地实现复用等功能,从而更好地开发项目。一般情况下比如创建头部组件的时候,我们会新建一个header的文件夹,然后再新建一个header.vue的文件 ③、router文件夹:该文件夹下有一个叫index.js文件,用于实现页面的路由跳转,具体使用请点击→vue-router传送门 ④、App.vue:作为我们的主组件,可通过使用开放入口让其他的页面组件得以显示。 ⑤、main.js:作为我们的入口文件,主要作用是初始化vue实例并使用需要的插件,小型项目省略router时可放在该处 .babelrc {//制定转码的规则 "presets": [ //env是使用babel-preset-env插件将js进行转码成es5,并且设置不转码的AMD,COMMONJS的模块文件,制定浏览器的兼容 ["env", { "modules": false, "targets": { "browsers": [">

1% "," last 2 versions "," not ie = 6.0.0 "," npm ":" > = 3.0.0 "}, / / limits the version required by the browser or client to run" browserslist ": [" > 1% "," last 2 versions "," not ie "

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report