Skip to content

环境搭建 ​

本节目标:理解“环境搭建”的核心思路,并能把它用于实际开发或面试表达。

说明:原 OneNote 中有图片引用,但图片未包含在导出目录中;本页保留了可用的文字与代码内容。 一、新建一个目录vue3-study;

二、初始化包:yarn init -y;

三、根目录下新增目录package,先增加两个包及其入口文件;

  • Reactivity/src/index.ts
  • Shared/src/index.ts

四、在这两个文件包下初始化package

  • 记得包名name为@vue开头,表示同一个域;
  • 在package.json中添加buildOptions:

五、添加打包指令:新建scripts/dev.js,scripts/build.js; 先安装基本包,创建rollup环境对资源进行打包 npm install

@babel/core
@babel/preset-env
Rollup
Rollup-plugin-typescript2
@rollup/plugin-node-resolve
Execa
rollup-plugin-babel
rollup-plugin-serve
cross-env
-D
编辑build.js文件:
`//` `1.`希望拿到`packages` 下的所有包
`const` `fs` `=`

require('fs'); //


 作用是单独开启一个进程进行打包
`const` `execa` `=`

require('execa'); //


 读取文件夹的目录
`const` `targets` `=`

fs.readdirSync('packages').filter(item


 `=>` `{`
    `//` 判断文件或文件夹的状态
    `return`

fs.statSync(packages/${item}).isDirectory() }) async


 `function`

build(target)


 `{`
    `//` `rollup` `-c` `--enviroment` `TARGET:shared`
    `//`  `{` `stdio:` `'inherit'` `}`表示当开启多个子进程中的输出结果会输出到父进程中
    `return`

execa(

'rollup', //


参数数组

['-c',

'--environment',


 `'TARGET:'` `+`

target],

         `{` `stdio:` `'inherit'` `}`

); } function

runAll(targets)


 `{`
    `let` `results` `=` `[];`
    `for`

(target


 `of`

targets)


 `{`

results.push(build(target));

     `}`
    `return`

Promise.all(results);


 `//` 多个文件夹并行打包

} //


 打包这些文件

runAll(targets).then(()


 `=>` `{`

console.log('


打包完毕

') })

在运行找包命名之前,我们还要在要目录下新建一个rollup.config.js配置文件: let path = require('path') let


 `ts` `=`

require('rollup-plugin-typescript2') let


 `resolvePlugin` `=`

require('@rollup/plugin-node-resolve').default //


 `1.`获取整个`packages`目录
`let` `packagesDir` `=`

path.resolve(__dirname,'packages'); //


 根据调用`rollup`时候的参数 来进行动态打包, 找到具体要打包哪个模块
`const` `name` `=`

process.env.TARGET; const


 `packageDir` `=`

path.resolve(packagesDir,name) //


 根据当前模块解析模块下`package.json`文件
`const` `currentResolve` `=`

(p)


 `=>`

path.resolve(packageDir,p) //


 我需要拿到`package.json` 中的内容
`const` `pkg` `=`

require(currentResolve('package.json')); //


 读取自己设定的对象
`const` `options` `=`

pkg.buildOptions //


 `"cjs",` `"esm-bundler",`

"global" const


 `outputConfig` `=` `{`

cjs:{

file:currentResolve(dist/${name}.cjs.js),

format:'cjs'

     `},`

global:{

file:currentResolve(dist/${name}.global.js),

format:'iife'

     `},`

'esm-bundler':{

file:currentResolve(dist/${name}.esm-bundler.js),

format:'esm'

} } //


 `rollup`的配置可以返回一个数组
`function`

createConfig(output){


 `//` 出口信息

console.log(output) // iife


格式要有`name`字段

output.name


 `=`

options.name;

output.sourcemap


 `=`

true;

     `return` `{`

input:currentResolve('src/index.ts'),

output,

plugins:[

ts({


 `//` 打包时候调用`ts`的配置文件
                `tsconfig:`

path.resolve(__dirname,'tsconfig.json')

             `}),`

resolvePlugin()


 `//` 解析后缀的
        `]`

} } export


 `default`

options.formats.map(f=>createConfig(outputConfig[f]))

在package.json中加上dev命令:

{
  "name": "vue",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "build":"node scripts/build.js"
  },
  "devDependencies": {
    "@rollup/plugin-node-resolve": "^13.0.0",
    "execa": "^5.1.0",
    "rollup": "^2.50.6",
    "rollup-plugin-typescript2": "^0.30.0",
    "typescript": "^4.3.2"
  }
}

添加tsconfig.json配置:

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */
    /* Basic Options */
    // "incremental": true,                         /* Enable incremental compilation */
    "target": "ESNEXT",                                /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "ESNEXT",                           /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [],                                   /* Specify library files to be included in the compilation. */
    // "allowJs": true,                             /* Allow javascript files to be compiled. */
    // "checkJs": true,                             /* Report errors in .js files. */
    // "jsx": "preserve",                           /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
    // "declaration": true,                         /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                      /* Generates a sourcemap for each corresponding '.d.ts' file. */
    "sourceMap": true,                           /* Generates corresponding '.map' file. */
    // "outFile": "./",                             /* Concatenate and emit output to single file. */
    // "outDir": "./",                              /* Redirect output structure to the directory. */
    // "rootDir": "./",                             /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                           /* Enable project compilation */
    // "tsBuildInfoFile": "./",                     /* Specify file to store incremental compilation information */
    // "removeComments": true,                      /* Do not emit comments to output. */
    // "noEmit": true,                              /* Do not emit outputs. */
    // "importHelpers": true,                       /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,                  /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,                     /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
    /* Strict Type-Checking Options */
    "strict": true,                                 /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                       /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                    /* Enable strict null checks. */
    // "strictFunctionTypes": true,                 /* Enable strict checking of function types. */
    // "strictBindCallApply": true,                 /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,        /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                      /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                        /* Parse in strict mode and emit "use strict" for each source file. */
    /* Additional Checks */
    // "noUnusedLocals": true,                      /* Report errors on unused locals. */
    // "noUnusedParameters": true,                  /* Report errors on unused parameters. */
    // "noImplicitReturns": true,                   /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,          /* Report errors for fallthrough cases in switch statement. */
    // "noUncheckedIndexedAccess": true,            /* Include 'undefined' in index signature results */
    // "noPropertyAccessFromIndexSignature": true,  /* Require undeclared properties from index signatures to use element accesses. */
    /* Module Resolution Options */
    // "moduleResolution": "node",                  /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                             /* Base directory to resolve non-absolute module names. */
    // "paths": {},                                 /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                              /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                             /* List of folders to include type definitions from. */
    // "types": [],                                 /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,        /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                        /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,                    /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,                /* Allow accessing UMD globals from modules. */
    /* Source Map Options */
    // "sourceRoot": "",                            /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                               /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                     /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                       /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
    /* Experimental Options */
    // "experimentalDecorators": true,              /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,               /* Enables experimental support for emitting type metadata for decorators. */
    /* Advanced Options */
    "skipLibCheck": true,                           /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true        /* Disallow inconsistently-cased references to the same file. */
  }
}

本站总访问 — 次