“This is the sixth day of my participation in the First Challenge 2022. For details: First Challenge 2022”

Writing in the front

I believe that many friends have implemented their own CLI tools gen command.

Let’s talk about how to implement a dev command and start the project with the dev command.

The preparatory work

With the previous several papers, here I believe that the students already know what I want to do next.

Let’s go back to SRC /index.ts and write

program.command('dev').description('Run varlet development environment').action(dev)
Copy the code

To receive a dev command, do it in SRC /commands/dev, exposing a dev method.

Dev is going to do

Let’s start by manually switching the runtime environment to dev

process.env.NODE_ENV = 'development'
Copy the code

Then we need to make sure that the project file exists where the name is entered

const SRC_DIR = resolve(process.cwd(), 'src')
ensureDirSync(SRC_DIR)
Copy the code

When this is done, you can start the project.

startServer

We use a startServer function to handle the startup business logic.

let server

const startServer = async () =>{
  server = await createServer()
  await server.listen()
  server.printUrls()
}
Copy the code

At this point, we are ready to start the service.

Let’s go to http://localhost:3000/

There will be students doubt for certain, my service is not up, how can not visit?

In fact, it is very simple, because we did not build the site, so we can not access the corresponding site resources.

For example, in the root directory of the project created on the CLI, create a new index.html file and see if it works in the browser.

Now that we know this, let’s finish building the site.

Site construction

We define a buildSiteEntry function to handle site building.

From the varlet-CLI source, we can see that buildSiteEntry does three things

1 Create a route for the mobile site

2 Create a route for the PC site

3 Generate site resources

In this article, we take 1 as an example to analyze. Those who are interested in 2 can visit our code repository.

As can be seen from the figure, we need to add the index.vue of Example under each component as a page to the route.

// Get the files in the SRC directory
const dir: string[] = await readdir('src')

// Splice the page address
const buildPath = (filename: string) = > resolve('src', filename, 'example'.'index.vue')

// Check whether the corresponding address exists
const existPath = (filename: string) = > pathExistsSync(buildPath(filename))

// Convert '/' with slash
const slashPath = (filename: string) = > slash(buildPath(filename))

// Generate the address
const examplePaths = dir.filter(existPath).map(slashPath) 
Copy the code

From the above we get all the page addresses, and the next step is to fill the route.

 const routes = examplePaths.map(
    (examplePath) = > `
  {
    path: 'The ${'/' + examplePath.match(//([-\w]+)/example/index.vue/)? .1]}',
    // @ts-ignore
    component: () => import('${examplePath}')
  }\
`
  )

  const source = `export default [\
  ${routes.join(', ')}] `
Copy the code

At this point we are done creating the route dynamically, and the next step is to write the file.

We create an outputFileSyncOnChange to handle file writes

const outputFileSyncOnChange = (path: string, code: string) => { ensureFileSync(path) const content = readFileSync(path, 'utf-8') if (content ! == code) { outputFileSync(path, code) } }Copy the code

Next we call the outputFileSyncOnChange function to write the route to the file.

outputFileSyncOnChange(resolve(process.cwd(), '.varlet/mobile.routes.ts'), source)
Copy the code

Next comes the generation of the site file.

We copy the site folder to the current running directory.

copy(resolve(__dirname, '.. /.. /site'), resolve(process.cwd(), '.varlet/site'))Copy the code

Next, let’s add some configuration for Vite

const inlineConfig =  {
  root: resolve(process.cwd(), '.varlet/site'),
  resolve: {
    extensions: ['.vue'.'.tsx'.'.ts'.'.jsx'.'.js'.'.less'.'.css'].alias: {'@config':  resolve(process.cwd(), '.varlet/site.config.json'),
      '@pc-routes':  resolve(process.cwd(), '.varlet/pc.routes.ts'),
      '@mobile-routes': resolve(process.cwd(), '.varlet/mobile.routes.ts')}},plugins: [
    vue({
      include: [/.vue$/./.md$/],
    }),
    md({ style: 'highlight.style' }),
  ],
}

server = await createServer(inlineConfig)
Copy the code

Then we run it again with you-cli-name dev.

It’s running

The last

This is the dev command, with a few cuts compared to varlet-cli dev.

For more details, please visit our repository. Welcome to STAR && PR