vue-cli scaffolding vue 및 vue-cli-service 명령에 대한 자세한 설명

만들다

vue create 뒤에는 많은 매개변수가 있습니다.

소스 코드는 다음과 같습니다.

program
  .command('create <app-name>')
  .description('create a new project powered by vue-cli-service')
  .option('-p, --preset <presetName>', 'Skip prompts and use saved or remote preset')
  .option('-d, --default', 'Skip prompts and use default preset')
  .option('-i, --inlinePreset <json>', 'Skip prompts and use inline JSON string as preset')
  .option('-m, --packageManager <command>', 'Use specified npm client when installing dependencies')
  .option('-r, --registry <url>', 'Use specified npm registry when installing dependencies (only for npm)')
  .option('-g, --git [message]', 'Force git initialization with initial commit message')
  .option('-n, --no-git', 'Skip git initialization')
  .option('-f, --force', 'Overwrite target directory if it exists')
  .option('--merge', 'Merge target directory if it exists')
  .option('-c, --clone', 'Use git clone when fetching remote preset')
  .option('-x, --proxy', 'Use specified proxy when creating project')
  .option('-b, --bare', 'Scaffold project without beginner instructions')
  .option('--skipGetStarted', 'Skip displaying "Get started" instructions')
  .action((name, cmd) => {
    const options = cleanArgs(cmd)

    if (minimist(process.argv.slice(3))._.length > 1) {
      console.log(chalk.yellow('\n Info: You provided more than one argument. The first one will be used as the app\'s name, the rest are ignored.'))
    }
    // --git makes commander to default git to true
    if (process.argv.includes('-g') || process.argv.includes('--git')) {
      options.forceGit = true
    }
    require('../lib/create')(name, options)
  })

위의 코드에서 매개변수 다음에 vue create가 오는 것을 분명히 알 수 있습니다.

vue 생성 실행 프로세스

뷰 생성 ===>

create.js ===>

Creator.js ===>

프리셋 로드 프리셋이 있는 경우 ===>

OS 모듈은 시스템 임시 폴더를 생성합니다( os 모듈은 일부 기본 시스템 작동 기능을 제공합니다 ) ===> 

원격 사전 설정이 있습니다. download-git-repo를 사용하여 창고를 다운로드하십시오 ===>

임시 폴더에서 내용을 가져와서 실제 폴더에 씁니다(fs 모듈에서 작동).

vue-cli-서비스

vue-cli-service는 프로젝트 패키징, 시작 및 기타 명령을 이 명령에 통합하는 create-react-app의 반응 스크립트와 같습니다. 소스 코드의 해당 패키지는 packages/vue/cli-service입니다.

그림과 같이:

항목 파일은 Service.js를 가리킵니다.

const Service = require('../lib/Service')
const service = new Service(process.env.VUE_CLI_CONTEXT || process.cwd())

const rawArgv = process.argv.slice(2)
const args = require('minimist')(rawArgv, {
  boolean: [
    // build
    'modern',
    'report',
    'report-json',
    'inline-vue',
    'watch',
    // serve
    'open',
    'copy',
    'https',
    // inspect
    'verbose'
  ]
})
const command = args._[0]

service.run(command, args, rawArgv).catch(err => {
  error(err)
  process.exit(1)
})

서비스.js

constructor() 인스턴스화 실행 ===>

this.pkg = this.resolvePkg(pkg) ===>

this.plugins = this.resolvePlugins(플러그인, useBuiltIn) ===>

instanceservice.run()

해결패키지(패키지)

pkg current 명령이 실행되는 디렉토리인 resolvePkg(pkg)를 통해 package.json을 구문 분석합니다.

반환 값은 package.json의 경로입니다.

resolvePlugins

1. 명령 아래에 명령 파일을 로드하고 형식을 다음과 같이 지정합니다.

[
  {
    id:'built-in:文件路径',
    apply: '命令文件'
  }
]

2. 종속성 및 devDependencies에 플러그인이 있는 경우 현재 플러그인 배열에 추가합니다.

플러그인이 있는지 판단하는 규칙:

id는 다음 정규식을 만족합니다.

/^(@vue\/|vue-|@[\w-]+(\.)?[\w-]+\/vue-)cli-plugin-/

this.pkg.optionalDependencies의 ID

3. 로컬 플러그인 로드

존재 여부 확인: this.pkg.vuePlugins && this.pkg.vuePlugins.service

체재:

[
  {
    id: `local:${file}`,
    apply: loadModule(`./${file}`, this.pkgContext)
  }
]

달리다

run에서 vue-cli-service 매개변수에 따라 해당 명령 파일을 얻고 명령 파일의 기능을 실행합니다.

serve.js 실행 프로세스 분석

webpack 구성, chainWebpack을 통해 가져오기

웹팩 구성 파일

실행 방법

여기서 어려움이 있는데 registerCommand가 정의되어 있는 부분인데 소스코드를 분석하면 알 수 있는데 registerCommand() 메소드는 그림과 같이 PluginApi에 정의되어 있다.

다음 코드의 this.service는 서비스 인스턴스를 가리킵니다.

여기에서 명령을 실행하기 전의 로직은 기본적으로 완료되었으며, 다음 단계는 이를 실행하는 것입니다.

 

 

Supongo que te gusta

Origin blog.csdn.net/qdmoment/article/details/104857781
Recomendado
Clasificación