fs-extra#readFileSync TypeScript Examples

The following examples show how to use fs-extra#readFileSync. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: snapshots-utils.ts    From ui5-language-assistant with Apache License 2.0 7 votes vote down vote up
function readInputXMLSnippet(
  testDir: string,
  removeRangeMarkers = true
): string {
  const inputPath = getInputXMLSnippetPath(testDir);
  const xmlOriginalContent = readFileSync(inputPath).toString("utf-8");
  if (removeRangeMarkers) {
    const xmlTextSnippetWithoutMarkers = stripRangeMarkers(xmlOriginalContent);
    return xmlTextSnippetWithoutMarkers;
  }
  return xmlOriginalContent;
}
Example #2
Source File: application-type.ts    From nx-plugins with MIT License 6 votes vote down vote up
function isNestJS(targets: TargetDefinitionCollection, host: Tree): boolean {
  const build = getTarget(targets, 'build');
  if (!build) {
    return false;
  }
  if (build.builder !== '@nrwl/node:build') {
    return false;
  }
  const mainPath = build.options.main.toString();
  let mainSource: string;
  if (host) {
    mainSource = host.read(mainPath).toString('utf-8');
  } else {
    mainSource = readFileSync(resolve(mainPath)).toString('utf-8');
  }
  const main = ts.createSourceFile(
    mainPath,
    mainSource,
    ts.ScriptTarget.Latest
  );
  return hasImport(main.statements, '@nestjs');
}
Example #3
Source File: index.ts    From nx-dotnet with MIT License 6 votes vote down vote up
export function updateFile(
  f: string,
  content: string | ((content: string) => string),
): void {
  ensureDirSync(path.dirname(tmpProjPath(f)));
  if (typeof content === 'string') {
    writeFileSync(tmpProjPath(f), content);
  } else {
    writeFileSync(
      tmpProjPath(f),
      content(readFileSync(tmpProjPath(f)).toString()),
    );
  }
}
Example #4
Source File: postInstall.ts    From cli with MIT License 6 votes vote down vote up
postInstall = async () => {
  // init cwd
  if (!process.env.INIT_CWD) {
    return;
  }
  const cwd = process.env.INIT_CWD;
  const pkgJsonFile = join(cwd, 'package.json');
  if (!existsSync(pkgJsonFile)) {
    return;
  }
  const pkg = JSON.parse(readFileSync(pkgJsonFile, 'utf-8'));
  const deps = Object.assign({}, pkg.dependencies, pkg.devDependencies);
  return {
    cwd,
    pkg,
    deps,
    pkgJsonFile,
  };
}
Example #5
Source File: utils.ts    From cli with MIT License 6 votes vote down vote up
findModuleFromNodeModules = async (
  moduleInfoList: ModInfo[],
  baseNodeModuleDir: string,
  fromNodeModulesPath: string,
  moduleMap: { [modName: string]: { version: string; path: string } } = {}
) => {
  for (const moduleInfo of moduleInfoList) {
    const { name, version } = moduleInfo;
    if (moduleMap[name] && semver.satisfies(moduleMap[name].version, version)) {
      continue;
    }

    const modulePath = join(fromNodeModulesPath, moduleInfo.name);
    let info = {
      path: modulePath,
    };
    let pkgJson: any = {};
    if (existsSync(modulePath)) {
      pkgJson = JSON.parse(
        readFileSync(join(info.path, 'package.json')).toString()
      );
    } else {
      info = getModuleCycleFind(
        moduleInfo.name,
        baseNodeModuleDir,
        fromNodeModulesPath
      );
      if (!info) {
        return;
      }
      pkgJson = JSON.parse(
        readFileSync(join(info.path, 'package.json')).toString()
      );
      if (!semver.satisfies(pkgJson.version, moduleInfo.version)) {
        return;
      }
    }
    moduleMap[moduleInfo.name] = {
      version: pkgJson.version,
      path: info.path,
    };
    const pkgDepsModuleInfoList: ModInfo[] = [];
    if (pkgJson.dependencies) {
      Object.keys(pkgJson.dependencies).map(modName => {
        const version = pkgJson.dependencies[modName];
        pkgDepsModuleInfoList.push({
          name: modName,
          version,
        });
      });
    }

    const childInfo = await findModuleFromNodeModules(
      pkgDepsModuleInfoList,
      baseNodeModuleDir,
      join(info.path, 'node_modules'),
      moduleMap
    );
    if (!childInfo) {
      return;
    }
  }
  return moduleMap;
}
Example #6
Source File: not-commonjs.test.ts    From cli with MIT License 6 votes vote down vote up
describe('test/not-commonjs.test.ts', () => {
  it('dev', async () => {
    const tsConfigFile = join(cwd, 'tsconfig.json');
    if (existsSync(tsConfigFile)) {
      await remove(tsConfigFile);
    }
    await copy(join(cwd, 'tsconfig.json.origin'), tsConfigFile);
    const { close, port, getData } = await run(cwd, {
      silent: true,
      fast: false,
    });
    const response = await fetch(`http://127.0.0.1:${port}/hello?name=midway`);
    const body = await response.text();
    const functions = await getData('functions');
    await close();
    const tsconfig = JSON.parse(readFileSync(tsConfigFile).toString());
    await remove(tsConfigFile);
    assert(functions.http);
    assert(body === 'hello world,midway');
    assert(tsconfig['ts-node'].compilerOptions.module === 'commonjs');
  });
});
Example #7
Source File: index.ts    From cli with MIT License 6 votes vote down vote up
private getTsConfig() {
    const { cwd } = this.core;
    this.core.debug('CWD', cwd);
    let { tsConfig } = this.options;
    let tsConfigResult;
    if (typeof tsConfig === 'string') {
      // if ts config is file
      if (existsSync(tsConfig)) {
        tsConfig = readFileSync(tsConfig).toString();
      }
      try {
        tsConfigResult = JSON.parse(tsConfig);
      } catch (e) {
        console.log('[midway-bin] tsConfig should be JSON string or Object');
        throw e;
      }
    }
    const projectFile = this.getProjectFile();
    if (!tsConfigResult) {
      if (!existsSync(projectFile)) {
        console.log(`[ Midway ] tsconfig.json not found in ${cwd}\n`);
        throw new Error('tsconfig.json not found');
      }
      try {
        tsConfigResult = JSON.parse(
          readFileSync(projectFile, 'utf-8').toString()
        );
      } catch (e) {
        console.log('[ Midway ] Read TsConfig Error', e.message);
        throw e;
      }
    }
    return tsConfigResult;
  }
Example #8
Source File: index.ts    From cli with MIT License 6 votes vote down vote up
async formatOptions() {
    const config = resolveMidwayConfig(this.core.cwd);
    if (config.exist) {
      this.isMidwayHooks = true;
      this.options.srcDir = config.source;
    }

    const packageJsonPath = join(this.core.cwd, 'package.json');
    if (existsSync(packageJsonPath)) {
      const pkgJson = JSON.parse(readFileSync(packageJsonPath).toString());
      this.midwayBinBuild = pkgJson['midway-bin-build'] || {};
      this.midwayCliConfig = pkgJson['midway-cli'] || {};
    }
  }
Example #9
Source File: main.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
function logPerformance() {
  const big: [string, number][] = [];
  const types: number[] = [];
  if (existsSync(perfDir)) {
    console.log("\n\n=== PERFORMANCE ===\n");
    for (const filename of readdirSync(perfDir, { encoding: "utf8" })) {
      const x = JSON.parse(readFileSync(joinPaths(perfDir, filename), { encoding: "utf8" })) as {
        [s: string]: { typeCount: number; memory: number };
      };
      for (const k of Object.keys(x)) {
        big.push([k, x[k].typeCount]);
        types.push(x[k].typeCount);
      }
    }
    console.log(
      "{" +
        big
          .sort((a, b) => b[1] - a[1])
          .map(([name, count]) => ` "${name}": ${count}`)
          .join(",") +
        "}"
    );

    console.log("  * Percentiles: ");
    console.log("99:", percentile(types, 0.99));
    console.log("95:", percentile(types, 0.95));
    console.log("90:", percentile(types, 0.9));
    console.log("70:", percentile(types, 0.7));
    console.log("50:", percentile(types, 0.5));
  }
}
Example #10
Source File: main.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
function getExpectedFailures(onlyRunAffectedPackages: boolean) {
  if (onlyRunAffectedPackages) {
    return undefined;
  }

  return new Set(
    (readFileSync(joinPaths(__dirname, "../expectedFailures.txt"), "utf8") as string)
      .split("\n")
      .filter(Boolean)
      .map((s) => s.trim())
  );
}
Example #11
Source File: index.ts    From nestjs-proto-gen-ts with MIT License 6 votes vote down vote up
private generate(path: string, pkg: string): void {
        let hbTemplate = resolve(__dirname, '../..', this.options.template);

        //If absolute path we will know have custom template option
        if (isAbsolute(path)) {
            hbTemplate = path;
        }

        if (!existsSync(hbTemplate)) {
            throw new Error(`Template ${hbTemplate} is not found`);
        }

        const tmpl = readFileSync(hbTemplate, 'utf8');

        if (this.options.verbose) {
            console.log(chalk.blueBright(`-- found: `) + chalk.gray(path));
        }

        this.output(path, pkg, tmpl);
    }
Example #12
Source File: application-type.ts    From nx-plugins with MIT License 6 votes vote down vote up
function isExpressJS(targets: TargetDefinitionCollection): boolean {
  const build = getTarget(targets, 'build');
  if (!build) {
    return false;
  }
  if (build.builder !== '@nrwl/node:build') {
    return false;
  }
  const mainPath = resolve(build.options.main.toString());
  const mainSource = readFileSync(mainPath).toString('utf-8');
  const main = ts.createSourceFile(
    mainPath,
    mainSource,
    ts.ScriptTarget.Latest
  );
  return (
    !hasImport(main.statements, '@nestjs') &&
    hasImport(main.statements, 'express')
  );
}
Example #13
Source File: file.ts    From cli with Apache License 2.0 6 votes vote down vote up
export function saveToEnvFile(
  pathToEnv: string,
  additionalEnvironment: Record<string, unknown>
) {
  ensureFileSync(pathToEnv);
  const environment = parse(readFileSync(pathToEnv, {encoding: 'utf-8'}));

  const updatedEnvironment = {
    ...environment,
    ...additionalEnvironment,
  };

  truncateSync(pathToEnv);
  for (const [key, value] of Object.entries(updatedEnvironment)) {
    appendFileSync(pathToEnv, `${key}=${value}${EOL}`);
  }
}
Example #14
Source File: build.ts    From malagu with MIT License 6 votes vote down vote up
async function renderEntry(entryTemplate: string, cfg: ApplicationConfig, entry: string) {
    ensureDir(PathUtil.getProjectHomePath());
    const server = ConfigUtil.getBackendMalaguConfig(cfg).server;
    const port = server?.port ?? 9000;
    let path = server?.path ?? '';
    let entryContent = readFileSync(entryTemplate, { encoding: 'utf8' });
    entry = entry.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    path = path.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    entryContent = entryContent
        .replace(/{{ entry }}/g, entry)
        .replace(/{{ port }}/g, port)
        .replace(/{{ path }}/g, path);
    await ensureDir(PathUtil.getBackendProjectDistPath());
    const newEntry = join(PathUtil.getBackendProjectDistPath(), 'gen-entry.js');
    writeFileSync(newEntry, entryContent, { encoding: 'utf8' });
    return newEntry;

}
Example #15
Source File: code-loader.ts    From malagu with MIT License 6 votes vote down vote up
protected async doLoad(codeDir: string, zip: JSZip, codeUri?: CodeUri) {
        const files = readdirSync(codeDir);
        for (const fileName of files) {
            const fullPath = join(codeDir, fileName);
            if (!codeUri?.include || !this.match(codeUri.include, fullPath)) {
                if (codeUri?.exclude && this.match(codeUri.exclude, fullPath)) {
                    continue;
                }
            }

            const file = statSync(fullPath);
            if (file.isDirectory()) {
                const dir = zip.folder(fileName);
                if (dir) {
                    await this.doLoad(fullPath, dir, codeUri);
                }
            } else {
                zip.file(fileName, readFileSync(fullPath), {
                    unixPermissions: '755'
                });
            }
        }
    }
Example #16
Source File: index.ts    From cli with MIT License 5 votes vote down vote up
async copyFile() {
    this.core.cli.log('Copy Files to build directory...');
    // copy packages config files
    const packageObj: any = this.core.service.package || {};
    if (this.core.config.specFile.path) {
      // backup original yml file
      await copy(
        this.core.config.specFile.path,
        resolve(this.midwayBuildPath, './f.origin.yml')
      );
      this.core.cli.log(
        `   - Copy ${this.core.config.specFile.path.replace(
          `${this.servicePath}/`,
          ''
        )} to ${'f.origin.yml'}`
      );
    }
    const exclude = [].concat(packageObj.exclude || []);
    if (!packageObj.lockFile) {
      exclude.push('yarn.lock');
      exclude.push('package-lock.json');
      exclude.push('pnpm-lock.yaml');
    }
    await copyFiles({
      sourceDir: this.servicePath,
      targetDir: this.midwayBuildPath,
      include: this.options.skipBuild
        ? [].concat(packageObj.include || [])
        : [this.options.sourceDir || 'src'].concat(packageObj.include || []),
      exclude,
      log: path => {
        this.core.cli.log(`   - Copy ${path}`);
      },
    });

    if (this.options.skipBuild) {
      // 跳过编译时也不处理package.json
      return;
    }
    if (this.codeAnalyzeResult.integrationProject) {
      let originPkgJson = {};
      try {
        const pkgJsonPath = join(this.servicePath, 'package.json');
        if (existsSync(pkgJsonPath)) {
          originPkgJson = JSON.parse(readFileSync(pkgJsonPath).toString());
        }
      } catch {
        //
      }
      await writeJSON(join(this.midwayBuildPath, 'package.json'), {
        ...originPkgJson,
        name: this.codeAnalyzeResult.projectType,
        version: '1.0.0',
        dependencies: this.codeAnalyzeResult.usingDependenciesVersion.valid,
      });
    }
    if (this.options.sharedDir) {
      this.options.sharedTargetDir = this.options.sharedTargetDir || 'static';
      this.core.cli.log(
        ` - Copy Shared Files to build directory(${this.options.sharedTargetDir})...`
      );
      this.options.sharedDir = this.transformToAbsolute(
        this.servicePath,
        this.options.sharedDir
      );
      this.options.sharedTargetDir = this.transformToAbsolute(
        this.midwayBuildPath,
        this.options.sharedTargetDir
      );
      console.log(this.options.sharedTargetDir);
      await copy(this.options.sharedDir, this.options.sharedTargetDir);
    }
    this.core.cli.log(' - File copy complete');
  }
Example #17
Source File: index.ts    From nx-dotnet with MIT License 5 votes vote down vote up
export function readFile(f: string) {
  const ff = f.startsWith('/') ? f : tmpProjPath(f);
  return readFileSync(ff).toString();
}
Example #18
Source File: index.ts    From cli with MIT License 5 votes vote down vote up
// vercel deploy
  async vercelDeploy() {
    // 执行 package 打包
    await this.core.invoke(['package'], true, {
      ...this.options,
      skipZip: true, // 跳过压缩成zip
      skipInstallDep: true,
    });

    await this.safeRemoveUselessFile();

    // 清理 package.json
    const pkgJsonFile = join(this.midwayBuildPath, 'package.json');
    if (existsSync(pkgJsonFile)) {
      const pkgJson = JSON.parse(readFileSync(pkgJsonFile).toString());
      delete pkgJson.devDependencies;
      writeFileSync(pkgJsonFile, JSON.stringify(pkgJson, null, 2));
    }

    this.core.cli.log('Start deploy by vercel/cli');
    try {
      const vercelPkg = require.resolve('vercel/package.json');
      const vercelPkgJson = JSON.parse(readFileSync(vercelPkg).toString());
      const vercelBin = join(dirname(vercelPkg), vercelPkgJson.bin.vercel);

      const args = [`--local-config=${this.vercelJsonFile}`];
      const token = this.options.token || process.env.VERCEL_TOKEN;
      if (token) {
        args.push(`--token=${token}`);
      }
      this.core.debug('Vercel Bin', vercelBin);
      this.core.debug('Vercel Deploy Args', args);
      await forkNode(`${vercelBin}`, args, {
        cwd: this.midwayBuildPath,
      });
      this.core.cli.log('Deploy success');
    } catch (e) {
      this.core.cli.log(`Deploy error: ${e.message}`);
    }
  }
Example #19
Source File: index.ts    From cli with MIT License 5 votes vote down vote up
// generate version.json to midwayBuildPath
  async generateVercelJson() {
    const funcList = this.getFunctionList();

    let vercelJson: any = {};
    if (existsSync(this.vercelJsonFile)) {
      vercelJson = JSON.parse(readFileSync(this.vercelJsonFile).toString());
    }

    const userDefinedEnv = filterUserDefinedEnv();
    if (!vercelJson.env) {
      vercelJson.env = {};
    }
    Object.assign(vercelJson.env, userDefinedEnv);

    if (!vercelJson.functions) {
      vercelJson.functions = {};
    }
    if (!vercelJson.functions) {
      vercelJson.functions = {};
    }

    if (!vercelJson.routes) {
      vercelJson.routes = [];
    }

    for (const func of funcList) {
      const { funcInfo, entryFileName } = func;
      if (!vercelJson.functions[entryFileName]) {
        vercelJson.functions[entryFileName] = {
          memory:
            funcInfo.memorySize ||
            this.core.service?.provider?.memorySize ||
            128, // 0 - 1024, step 64
          maxDuration:
            funcInfo.timeout || this.core.service?.provider?.timeout || 10, // 0 - 10
        };
      }

      if (!funcInfo.events || !Array.isArray(funcInfo.events)) {
        continue;
      }

      for (const event of funcInfo.events) {
        const trigger = event?.http;
        if (!trigger) {
          continue;
        }

        // * to 正则表达式
        const path = (trigger.path || '/*').replace(/\*/g, '.*');
        vercelJson.routes.push({
          src: path,
          dest: entryFileName,
          methods: convertMethods(trigger.method),
        });
      }
    }

    writeFileSync(this.vercelJsonFile, JSON.stringify(vercelJson, null, 2));
  }
Example #20
Source File: remarkVue.spec.ts    From vite-plugin-md-preview with MIT License 5 votes vote down vote up
test('remarkVue', async () => {
  const a = await remark()
    .use(remarkVue, { file: 'test.md' })
    .process(readFileSync(path.join(__dirname, './test.md')))
    .then((v) => {
      console.log(v.value);
    });
});
Example #21
Source File: index.ts    From cli with MIT License 5 votes vote down vote up
async bundle() {
    if (!this.options.bundle) {
      return;
    }
    const nccPkgJsonFile = require.resolve('@vercel/ncc/package');
    const nccPkgJson = JSON.parse(readFileSync(nccPkgJsonFile).toString());
    const nccCli = join(nccPkgJsonFile, '../', nccPkgJson.bin.ncc);

    const entryList = await globby(['*.js'], {
      cwd: this.midwayBuildPath,
    });

    if (!entryList.length) {
      return;
    }

    this.core.cli.log('Build bundle...');

    await Promise.all(
      entryList.map(async entry => {
        const entryName = entry.slice(0, -3);
        await forkNode(
          nccCli,
          ['build', entry, '-o', 'ncc_build_tmp/' + entryName, '-m'],
          {
            cwd: this.midwayBuildPath,
          }
        );
        await remove(join(this.midwayBuildPath, entry));
        await move(
          join(
            this.midwayBuildPath,
            'ncc_build_tmp/' + entryName + '/index.js'
          ),
          join(this.midwayBuildPath, entry)
        );
      })
    );

    await remove(join(this.midwayBuildPath, 'node_modules'));
    await remove(join(this.midwayBuildPath, 'dist'));
    await remove(join(this.midwayBuildPath, 'ncc_build_tmp'));
    await remove(join(this.midwayBuildPath, 'src'));
  }
Example #22
Source File: server.ts    From elemental4 with GNU General Public License v3.0 5 votes vote down vote up
export function serverCreate() {
    app = express();
    io = SocketIO();
    io.origins('*:*');

    newEntryEmitter.on((entry) => {
        io.sockets.emit('new-entry', entry)
    })
        
    // Remove Express Header
    app.use((req,res,next) => {
        res.removeHeader("X-Powered-By");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Headers", "*");
        res.setHeader("Access-Control-Expose-Headers", "Content-Length,Elem4-Entry-Length");

        next();
    });

    app.get('/', (r,res) => res.send("Elemental 4 " + pkg.version));
    app.get('/ping', (r,res) => res.send("pong"));
    app.get('/elemental.json', (r,res) => {
        res.send({
            type: 'elemental4',
            name: SERVER_NAME,
            description: SERVER_DESCRIPTION,
            serverVersion: pkg.version,
            icon: SERVER_ICON,
            dbId: getDbId()
        })
    });
    
    // Add api calls
    app.use(require("./api/api-v1").default());

    // Create an HTTP service.
    if (ENABLE_HTTP) {
        if(ENABLE_HTTPS) {
            // redirectify
            createHTTPServer((req, res) => {
                const host = req.headers["host"];
                const url = "https://" + host + req.url;
                res.statusCode = 302;
                res.setHeader("Location", url);
                res.end("Moved to <a href='" + url + "'>" + url + "</a>");
            }).listen(HTTP_PORT, () => {
                log.info("HTTP server started (Redirecting to HTTPS). http://localhost:" + HTTP_PORT);
            });
        } else {
            // make the server on http
            const s = createHTTPServer(app).listen(HTTP_PORT, () => {
                log.info("HTTP server started. http://localhost:" + HTTP_PORT);
            });
            io.listen(s);
        }
    }
    
    // Create an HTTPS service identical to the HTTP service.
    if (ENABLE_HTTPS) {
        const httpsOptions: ServerOptions = {
            key: readFileSync(HTTPS_KEY),
            cert: readFileSync(HTTPS_CERT),
        }
        const s = createHTTPSServer(httpsOptions, app).listen(HTTPS_PORT, () => {
            log.info("HTTPS server started. https://localhost:" + HTTPS_PORT);
        });
        io.listen(s);
    }
}
Example #23
Source File: index.ts    From cli with MIT License 5 votes vote down vote up
async installDevDep() {
    this.core.cli.log('Install development dependencies...');
    let isNeedSkipInstallNodeModules = false;
    if (existsSync(join(this.servicePath, 'node_modules'))) {
      let originPkgJson: any = {};
      try {
        const pkgJsonPath = join(this.servicePath, 'package.json');
        if (existsSync(pkgJsonPath)) {
          originPkgJson = JSON.parse(readFileSync(pkgJsonPath).toString());
        }
      } catch {
        //
      }
      const allDepMap = Object.assign(
        {},
        originPkgJson.dependencies,
        originPkgJson.devDependencies
      );
      const allDepList = Object.keys(allDepMap);
      const notInstalled = allDepList.find(depName => {
        return !existsSync(join(this.servicePath, 'node_modules', depName));
      });
      if (!notInstalled) {
        isNeedSkipInstallNodeModules = true;
      }
    }

    if (!isNeedSkipInstallNodeModules) {
      await this.npmInstall({
        baseDir: this.servicePath,
      });
      this.core.cli.log(' - Install development dependencies complete...');
    } else {
      this.core.cli.log(' - Find node_modules and skip...');
    }

    // 分析midway version
    const cwd = this.getCwd();
    const faasModulePath = findNpmModule(cwd, '@midwayjs/faas');
    if (faasModulePath) {
      const pkgJson = JSON.parse(
        readFileSync(join(faasModulePath, 'package.json')).toString()
      );
      this.midwayVersion = pkgJson.version[0];
    }
    this.setStore('midwayVersion', this.midwayVersion, true);
    this.core.debug('midwayVersion', this.midwayVersion);
  }
Example #24
Source File: index.ts    From cli with MIT License 5 votes vote down vote up
async bundle() {
    if (!this.options.bundle) {
      return;
    }
    const nccPkgJsonFile = require.resolve('@vercel/ncc/package');
    const nccPkgJson = JSON.parse(readFileSync(nccPkgJsonFile).toString());
    const nccCli = join(nccPkgJsonFile, '../', nccPkgJson.bin.ncc);
    const outDir = join(this.core.cwd, this.getOutDir());

    let preloadCode = '// midway bundle';
    const preloadFile = 'midway_bundle_entry.js';
    const requireList = await globby(['**/*.js'], {
      cwd: outDir,
    });

    preloadCode += requireList
      .map((file, index) => {
        return `require('./${file}');`;
      })
      .join('\n');

    const configurationFilePath = join(outDir, 'configuration.js');
    if (existsSync(configurationFilePath)) {
      preloadCode += `
      const configuration = require('./configuration.js');
      if (typeof configuration === 'object') {
        const configurationKey = Object.keys(configuration).find(key => typeof configuration[key] === 'function');
        if (configurationKey) {
          exports.configuration = configuration[configurationKey];
        }
      } else {
        exports.configuration = configuration;
      }
      `;
    }
    writeFileSync(join(outDir, preloadFile), preloadCode);

    this.core.cli.log('Build bundle...');
    await forkNode(
      nccCli,
      ['build', preloadFile, '-o', 'ncc_build_tmp', '-m'],
      {
        cwd: outDir,
      }
    );
    const tmpFile = join(tmpdir(), `midway_bundle_${Date.now()}.js`);
    await move(join(outDir, 'ncc_build_tmp/index.js'), tmpFile);
    await remove(outDir);
    await move(tmpFile, join(outDir, 'bundle.js'));
    await remove(tmpFile);
    this.core.cli.log(
      `Success compile to ${relative(
        process.cwd(),
        join(outDir, 'bundle.js')
      )}.`
    );
    this.core.cli.log(
      'You can use it through the configurationModule parameter in the bootstrap file.'
    );
  }
Example #25
Source File: file.ts    From cli with Apache License 2.0 5 votes vote down vote up
export function flushEnvFile(projectPath: string) {
  const envPath = join(projectPath, '.env');
  const env = readFileSync(envPath, 'utf-8');
  truncateSync(envPath);
  return env;
}
Example #26
Source File: generate-packages.ts    From DefinitelyTyped-tools with MIT License 5 votes vote down vote up
mitLicense = readFileSync(joinPaths(__dirname, "..", "LICENSE"), "utf-8")
Example #27
Source File: constants.ts    From elemental4 with GNU General Public License v3.0 5 votes vote down vote up
env = dotenv.parse(readFileSync("./.env"))
Example #28
Source File: templates.ts    From mordred with MIT License 5 votes vote down vote up
graphqlDefinitionTemplate = readFileSync(
  join(__dirname, '../templates/graphql.d.ts'),
  'utf8'
)
Example #29
Source File: templates.ts    From mordred with MIT License 5 votes vote down vote up
template = readFileSync(
  join(__dirname, '../templates/graphql.ejs'),
  'utf8'
)