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

How to use vue-cli-server

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the relevant knowledge of how to use vue-cli-server, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this article on how to use vue-cli-server. Let's take a look at it.

I. entrance

We can see that npm run dev is actually vue-cli-service serve in package.json. When we install vue-cli, we can install our vue-cli-service together, and then execute npm install vue-cli-service-save-dev so that we can find vue-cli-service in the. / node_modules/.bin directory. The related code is as follows:

@ IF EXIST "% ~ dp0\ node.exe" ("% ~ dp0\ node.exe"% ~ dp0\..\ @ vue\ cli-service\ bin\ vue-cli-service.js "% *) ELSE (@ SETLOCAL @ SET PATHEXT=%PATHEXT:;.JS;=;% node"% ~ dp0\..\ @ vue\ cli-service\ bin\ vue-cli-service.js "% *)

Entry path:. / node_modules/@vue/cli-service/bin/vue-cli-service.js.

We can also take a look at our vue-cli-service.js core code, as follows:

Const Service = require ('.. / lib/Service') / / instantiate Service// VUE_CLI_CONTEXT to undefined So the values passed in are process.cwd () and const service = new Service (process.env.VUE_CLI_CONTEXT | | process.cwd ()) const rawArgv = process.argv.slice (2) / / minimist parsing tool to parse the command line parameters const args = require ('minimist') (rawArgv, {boolean: [/ / build' modern', 'report',' report-json', 'watch', / / serve' open') 'copy',' https', / / inspect 'verbose']}) / {/ / _: [' serve'], / / modern: false,// report: false,// 'report-json': false,// watch: false,// open: false,// copy: false,// https: false,// verbose: false / /} const command = args._ [0] / / execute the service method: 'serve', agrs, [' serve','--open',...] service.run (command, args, rawArgv) .catch (err = > {error (err) process.exit (1)})

II. Initialize configuration

The code is as follows:

Module.exports = class Service {constructor (context, {plugins, pkg, inlineOptions) UseBuiltIn} = {}) {process.VUE_CLI_SERVICE = this this.initialized = false this.context = context this.inlineOptions = inlineOptions this.webpackChainFns = [] this.webpackRawConfigFns = [] this.devServerConfigFns = [] this.commands = {} this.pkgContext = context / / get the dependent this.pkg = this.resolvePkg (pkg) in package.json / / if there is an inline plug-in Do not use the plug-in found in package.json / / the resulting plugins is the built-in plug-in + @ vue/cli-plugin-* / / {id: 'xxx',apply: require (' xxx')} this.plugins = this.resolvePlugins (plugins, useBuiltIn) / / parse the default mode / / {serve: 'development', / / build:' production' used by each command / / inspect: 'development'} this.modes = this.plugins.reduce ((modes, {apply: {defaultModes}}) = > {return Object.assign (modes, defaultModes)}, {})} / /.}

We get the dependencies in package.json, read our package.json file through the read-pkg package, and initialize the relevant plug-ins after returning a value to our this.pkg; in json format. The code is as follows:

ResolvePlugins (inlinePlugins, useBuiltIn) {const idToPlugin = id = > ({id: id.replace (/ ^.\ / /, 'built-in:'), apply: require (id)}) let plugins const builtInPlugins = [. / commands/serve','. / commands/build','. / commands/inspect','. / commands/help' / / config plugins are order sensitive'. / config/base','. / config/css','. / config/dev','. / config/prod' '. / config/app'] .map (idToPlugin) if (inlinePlugins) {/ /.} else {/ / Development environment dependency + production environment dependency Get the cli-plugin-* plug-in const projectPlugins = Object.keys (this.pkg.devDependencies | | {}) .concat (Object.keys (this.pkg.dependencies | | {})) .filter (isPlugin) / / verify whether it is the vue-cli plug-in cli-plugin-* .map (idToPlugin) plugins = builtInPlugins.concat (projectPlugins)} / /.}

1. Parse each command by initializing the mode. The code is as follows:

/ / parse the default mode used by each command / / {serve: 'development', / / build:' production', / / inspect: 'development'} this.modes = this.plugins.reduce ((modes, {apply: {defaultModes}}) = > {return Object.assign (modes, defaultModes)}, {})

Then defaultModes this file everywhere by default in the inline plug-in as follows:

/ / serve.js module.exports.defaultModes = {serve: 'development'}

Third, parsing command parameters

We parse the command line parameters here through the minimist parsing tool, as shown below:

Const args = require ('minimist') (rawArgv, {boolean: [/ / build / / serve' open',' copy', 'https',]}) / /' serve', agrs, ['serve','--open',...]

IV. Loading plug-ins

By running the service.run method, loading environment variables, loading user configuration, and applying plug-ins, the code is as follows:

Async run (name, args = {}, rawArgv = []) {const mode = args.mode | | (name = = 'build' & & args.watch? 'development': this.modes [name]) / / load environment variables, load user configuration, and apply plug-in this.init (mode) args._ = args._ | | [] / / get the corresponding command let command = this.commands [name] / / from the registered command set. Const {fn} = command return fn (args, rawArgv)}

1. Load the environment variable. We read the environment variable from the .env. (mode) file in the root directory of the project and write it to process.env (declare that the environment variable must be VUE_APP_*, or it will be filtered out) as follows:

Init (mode = process.env.VUE_CLI_MODE) {/ / load development.env environment variable if (mode) {this.loadEnv (mode)} this.loadEnv () / /...} / / load environment variable method (part) loadEnv (mode) {/ / project path / .env.development const basePath = path.resolve (this.context) `.env ${mode? `. ${mode}`: ``} `) / project path / .env.development.local const localPath =` ${basePath} .local` const load = path = > {const env = dotenv.config ({path, debug: process.env.DEBUG}) / / the config function of dotenv (located in node_modules/dotenv) will be called first The format {parsed: {YOUR_ENV_KEY: 'the environment variable value you set'}} will eventually be returned and written to process.env dotenvExpand (env) logger (path, env)} load (localPath) load (basePath) if (mode) {const defaultNodeEnv = (mode = = 'production' | | mode = =' test')? Mode: 'development' if (shouldForceDefaultEnv | | process.env.NODE_ENV = = null) {process.env.NODE_ENV = defaultNodeEnv}

2. Load user configuration

We can do this by reading the configuration inside the vue.config.js file. The code is as follows:

Init (mode = process.env.VUE_CLI_MODE) {/ / load user configuration const userOptions = this.loadUserOptions () this.projectOptions = defaultsDeep (userOptions, defaults ())}

3. Application plug-in

/ / const idToPlugin = id = > ({/ / id: id.replace (/ ^.\ / /, 'built-in:'), / / apply: require (id) / /}) init (mode = process.env.VUE_CLI_MODE) {/ / Application plug-in this.plugins.forEach (({id, apply}) = > {apply (new PluginAPI (id, this)) This.projectOptions)}) / / apply webpack configuration if (this.projectOptions.chainWebpack) {this.webpackChainFns.push (this.projectOptions.chainWebpack)} if (this.projectOptions.configureWebpack) {this.webpackRawConfigFns.push (this.projectOptions.configureWebpack)} from the project configuration file

There is an apply property when you initialize the plug-in (the resolvePlugins method), and you can import the corresponding plug-in by calling this method, which is where the serve.js method is called.

4. Register the command

We are registering the serve command in service with the following code:

/ serve.jsapi.registerCommand ('serve', {description:' start development server', usage: 'vue-cli-service serve [options] [entry]', options: {}}, async function serve (args) {/ /...})

5. Configure startup service

Finally, we pass the method passed when registering the serve in the executed serve.js. Then after webpack obtains the configuration, it passes it to webpackDevServer by instantiating Compiler, and automatically compiles and updates it through webpackDevServer. The code is as follows:

/ / serve.js serve function async function serve (args) {/ / create webpack compiler const compiler = webpack (webpackConfig) / / compiler.run () to complete a compilation package / / create a local service const server = new WebpackDevServer (compiler, Object.assign ({clientLogLevel: 'none', historyApiFallback: {disableDotRule: true, rewrites: [{from: /. / To: path.posix.join (options.baseUrl, 'index.html')}]}, contentBase: api.resolve (' public'), watchContentBase:! isProduction, hot:! isProduction, quiet: true, compress: isProduction, publicPath: options.baseUrl, overlay: isProduction / / TODO disable this? False: {warnings: false, errors: true}}, projectDevServerOptions, {https: useHttps, proxy: proxySettings,}) return new Promise ((resolve, reject) = > {compiler.hooks.done.tap ('vue-cli-service serve', stats = > {/ /.}) / /. Server.listen (port, host, err = > {if (err) {reject (err)}})})}

We get the webpack configuration here: api.resolveWebpackConfig (), and then create the webpack-dev-server instance by obtaining the middleware entry of devServer configuration injection webpack-dev-server and hot-reload (HRM), and after starting webpack-dev-server, the compiled files are not seen in the target folder, and the real-time compiled files are saved in memory.

This is the end of the article on "how to use vue-cli-server". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to use vue-cli-server". If you want to learn more, you are welcome to follow the industry information channel.

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