通过节点自动化Webpack项目设置

时间:2017-07-01 16:16:57

标签: javascript node.js terminal

我的目标是通过node命令crateEntireWepbackProject.js文件设置webpack项目。

我想从js文件在shell上执行命令,所以我可以让它们自动运行,稍后还可以包含项目的自定义规范。

js文件不是来自webpack,而是具有从头开始创建wepback项目的命令,并通过键入node createEntireWebpackProject.js

进行安装等。

1 个答案:

答案 0 :(得分:1)

您无需从头开始编写。最佳做法是使用yeoman。有很多带webpack的生成器。例如:

const Generator = require('yeoman-generator');
const mkdirp = require('mkdirp');
const path = require('path');

module.exports = class extends Generator {
  prompting() {
    this.log('Welcome to the classy example generator!');

    const prompts = [
      {
        type: 'input',
        name: 'name',
        message: 'Name?',
        default: this.appname,
      }];

    return this.prompt(prompts).then((props) => {
      this.props = props;
    });
  }

  default() {
    if (path.basename(this.destinationPath()) !== this.props.name) {
      this.log(
        `Your application must be inside a folder named ${this.props.name}`);
      this.log('I\'ll automatically create this folder.');
      mkdirp(this.props.name);
      this.destinationRoot(this.destinationPath(this.props.name));
    }
  }

  writing() {
    this.createPackageJson();
    this.copyFiles();
    this.fillTemplates();
    this.makeCommands();
  }

  install() {
    this.npmInstall(['bunyan', 'dotenv-safe'], { save: true });
    this.npmInstall(['eslint', 'eslint-config-airbnb-base', 'eslint-plugin-import', 'jest'], { 'save-dev': true });
  }

  createPackageJson() {
    this.fs.extendJSON('package.json', {
      name: this.props.name,
      version: '0.1.0',
      main: 'src/app.js',
      scripts: {
        cs: 'eslint src/* __tests__/*',
        'cs:fix': 'eslint src/* __tests__/* --fix',
        start: 'node src/app.js',
        test: 'npm run cs && jest',
      },
      dependencies: {},
      devDependencies: {},
      engines: {
        node: '^8.1.0',
      },
      private: true,
      jest: {
        testEnvironment: 'node',
        transform: {},
        collectCoverage: true,
      },
    });
  }

  copyFiles() {
    [
      '.dockerignore',
      '.eslintrc.json',
      'src/app.js',
    ].forEach(name => this.fs.copy(this.templatePath(name), this.destinationPath(name)));
  }

  fillTemplates() {
    this.fs.copyTpl(
      this.templatePath('README.md'),
      this.destinationPath('README.md'),
      {
        name: this.props.name,
      });
  }
  makeCommands() {
      this.spawnCommandSync('git' ['init']);
      this.spawnCommandSync('git', ['add', '.']);
      this.spawnCommandSync('git', ['commit', '-am', '"yo scaffolded app"']);
  }
};