This article is from a learning sharing by @Xiaoming, a team member. I hope to share and discuss with you.

Seek to accumulate silicon step so that thousands of miles, dare to explore the beauty of life.

background

Recently, in my spare time studying ViteJs’s new framework, I found that to create a new Vite based project, I used the following command:

npm init @vitejs/app
Copy the code

This is completely different from the familiar CLI commands used to create Vue projects:

vue create project-name
Copy the code

“Can you use NPM to create projects without installing scaffolding tools?” A little inquisitive inquiry.

What does this command NPM init. vitejs/app do?

This command is to create a new Vite project based on a template. This template can be Vue/React or something else. So how exactly is it created? So with that in mind let’s go over NPM init.

Review the NPM init

NPM init should be familiar to most of us. We usually use NPM init to initialize a package.json file to start a project. Most people only use this command, but it can carry parameters, right? What does this parameter do? For me, a big-screen CV programmer, flip is a Google. The Googlers tell us nPM-init:

NPM init

is typically used to create a new or existing NPM package.

Initializer in this case is an NPM package named create-< Initializer > that will be installed by NPX and the script corresponding to the bin property in its package.json will be executed. Package. json is created or updated and some initialization related operations are run.

The official notes also give some examples of the corresponding commands:

The command equivalent
npm init foo npx create-foo
npm init @usr/foo npx @usr/create-foo
npm init @usr npx @usr/create

The command at the beginning of this article, NPM init. vitejs/app, matches the second example exactly, which should look like this:

npm init @vitejs/app -> npx @vitejs/create-app
Copy the code

NPM init @vitejs/app: NPM init @vitejs/app: NPM init @vitejs/app: NPM init @vitejs/app: NPM init @vitejs/app

The ViteJs package folder does contain a create-app directory, so let’s take a closer look at what is in this directory.

What does the @Vitejs/Create-app project do?

Find the bin entry in package.json in the create-app folder:

{
  "name": "@vitejs/create-app"./ /... Yes, this is it
  "bin": {
    "create-app": "index.js"."cva": "index.js"}},Copy the code

The bin attribute is used to configure the index.js file for create-app execution, so we can see what happens in the index.js file.

// https://github.com/vitejs/vite/blob/main/packages/create-app/index.js

// omit non-critical code
const TEMPLATES = [
  yellow('vanilla'),
  green('vue'),
  green('vue-ts'),
  / /...
]

async function init() {
  let targetDir = argv._[0]
  if(! targetDir) {// Step 1: Determine the Project name entered by the user
    const { name } = await prompt({
      type: 'input'.name: 'name'.message: `Project name:`.initial: 'vite-project'
    })
    targetDir = name
  }

  const root = path.join(cwd, targetDir)
  console.log(`\nScaffolding project in ${root}. `)
  
  // Step 2: Check whether there is an empty directory with the same name
  if(! fs.existsSync(root)) { fs.mkdirSync(root, {recursive: true})}else {
    const existing = fs.readdirSync(root)
    if (existing.length) {
        / /...}}// Step 3 verify and select the template
  let template = argv.t || argv.template
  let message = 'Select a template:'
  if(! template || ! isValidTemplate) {const { t } = await prompt({
      type: 'select'.name: 't',
      message,
      choices: TEMPLATES
    })
    template = stripColors(t)
  }

  const templateDir = path.join(__dirname, `template-${template}`)

  const write = (file, content) = > {
    const targetPath = renameFiles[file]
      ? path.join(root, renameFiles[file])
      : path.join(root, file)
    if (content) {
      fs.writeFileSync(targetPath, content)
    } else {
      copy(path.join(templateDir, file), targetPath)
    }
  }
  // Step 4: Copy and write the file
  const files = fs.readdirSync(templateDir)
  for (const file of files.filter((f) = >f ! = ='package.json')) {
    write(file)
  }

  const pkg = require(path.join(templateDir, `package.json`))

  // Step 5: Copy package.json
  write('package.json'.JSON.stringify(pkg, null.2))
  / /... Prompt 'NPM install/NPM run dev'
}

// omit function function...
init().catch((e) = > {
  console.error(e)
})
Copy the code

The main logic of the above code is as follows:

  • Step 1: Determine Project name, user input or default;
  • Step 2: Check whether the local directory with the same name exists and whether the directory is empty.
  • Step 3: Select template vue, VUE-ts, react, etc.
  • Part four (core) : Match to the project according to the selected templatetemplate-To copy all files in the directory to the local project directory.
  • Step 5: Copy the new package.json with name changed to the new project and prompt you to install dependencies and run them.

So far we have made it clear that NPM init. vitejs/app is executed by executing the script file specified by bin in create-app. What this script file (in this case index.js) does is use Node to copy all the template files to the local project directory based on some configuration and template projects, thus completing a series of operations to create a project from a template.

Why go to so much trouble to create CLI scaffolding for your project? Wait and see.

npm init VS vue create

When we use Vue Create to create projects, behind the scenes are the capabilities that VUE-CLI gives us. So we have to install vuE-CLI first before we can use it to create projects. NPM init skips the CLI part and is implemented based on a specified script, so it has some advantages over Vue Create:

  • Projects are tools, simpler and more direct;
  • There is no need to install additional CLI tools, more than one tool is more than one use cost;
  • Easy to update, no need to maintain templates and CLI tools at the same time.

So, overall, creating projects using NPM init is simpler and more pure.

Learn more about package.json

Json file’s bin property. What’s the difference between bin and main?

main bin
The attribute is a Module ID, which is the main entry point to the program. If not set, the default is index.js If the NPM package has the bin attribute, then the executable file of the NPM package will be linked to the./node_modules/.bin of the current project, and then it will be easy to execute the package from the command line, such as: Node_modules /.bin/myapppackage.json bin

I have to say that every attribute in package.json has its own purpose, and only by reading and analyzing its meaning and usage can we have the spark to create the wheel!

What can you do after learning?

The company’s new projects keep emerging, currently the project is still doing the reconstruction of the micro front end, each sub-module in the micro front end needs to use a template Ctrl + C/Ctrl + V to create, although it is a small case for us CV programmers, but if we have our own create-app, Wouldn’t it be nicer if we flipped a NPM init. company/app?

Not only that, we can also establish the company’s internal or external template library project, will all commonly used template project maintenance into a project, unified maintenance and management, is not too fast? The hole has been dug and the work has been arranged.

That is all the content of this sharing. I hope it will help you

Like the words don’t forget to move your fingers, like, collect, pay attention to three even a wave away.


About us

We are the front end team, left hand component library, right hand tool library, all kinds of technology savage growth.

A man can’t run as fast as a crowd can run. Welcome to join our team, the year of the Ox is booming forward.