YMFE / yapi

YApi 是一个可本地部署的、打通前后端及QA的、可视化的接口管理平台
http://yapi.smart-xwork.cn/
Apache License 2.0
27.3k stars 4.78k forks source link

二次开发运行或打包报swagger-client/lib/http.js等Module parse failed错误 #1865

Closed sagexy closed 4 years ago

sagexy commented 4 years ago

版本号

yapi: 1.9.2 node: v8.17.0 npm: 6.13.4

什么问题

开发或运行的时候报错误

[error] in ./~/swagger-client/lib/http.js
Module parse failed: /Users/xy/WorkSpace/gogs/yapi/vendors/node_modules/swagger-client/lib/http.js Unexpected token (41:6)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (41:6)
 @ ./~/swagger-client/lib/index.js 12:36-53

[error] in ./~/swagger-client/lib/resolver.js
Module parse failed: /Users/xy/WorkSpace/gogs/yapi/vendors/node_modules/swagger-client/lib/resolver.js Unexpected token (123:38)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (123:38)
 @ ./~/swagger-client/lib/index.js 14:40-61

[error] in ./~/swagger-client/lib/subtree-resolver/index.js
Module parse failed: /Users/xy/WorkSpace/gogs/yapi/vendors/node_modules/swagger-client/lib/subtree-resolver/index.js Unexpected token (20:6)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (20:6)
 @ ./~/swagger-client/lib/index.js 16:46-75

✖ [10:15:45] 3 errors in compiling process.
[error] in ./~/swagger-client/lib/http.js
Module parse failed: /Users/xy/WorkSpace/gogs/yapi/vendors/node_modules/swagger-client/lib/http.js Unexpected token (41:6)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (41:6)
 @ ./~/swagger-client/lib/index.js 12:36-53

[error] in ./~/swagger-client/lib/resolver.js
Module parse failed: /Users/xy/WorkSpace/gogs/yapi/vendors/node_modules/swagger-client/lib/resolver.js Unexpected token (123:38)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (123:38)
 @ ./~/swagger-client/lib/index.js 14:40-61

[error] in ./~/swagger-client/lib/subtree-resolver/index.js
Module parse failed: /Users/xy/WorkSpace/gogs/yapi/vendors/node_modules/swagger-client/lib/subtree-resolver/index.js Unexpected token (20:6)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (20:6)
 @ ./~/swagger-client/lib/index.js 16:46-75

image

如何复现此问题

  1. git clone 代码
  2. npm install
  3. npm run dev / npm run build-client

然后就是报以上的错误

什么浏览器

Chrome 83

什么系统(Linux, Windows, macOS)

macOS 10.15

jiangjunfeng98 commented 4 years ago

exts/yapi-plugin-import-swagger/index.js 置为 false ,可以临时关闭。

// exts/yapi-plugin-import-swagger/index.js
module.exports = {
  server: false,
  client: false
}
JoveYu commented 4 years ago

同样的错误,设置为fasle是什么意思? 那样不会导致编译后缺少功能吗

121595113 commented 4 years ago

ykit.config.js添加babel-loader可解,希望有人可以提一个pr修复

 baseConfig.module.preLoaders.push({
     test: /\.(js|jsx)$/,
     include: [path.resolve(__dirname, './node_modules/swagger-client')],
     loader: 'babel-loader'
});
doramart commented 3 years ago

ykit.config.js添加babel-loader可解,希望有人可以提一个pr修复

 baseConfig.module.preLoaders.push({
     test: /\.(js|jsx)$/,
     include: [path.resolve(__dirname, './node_modules/swagger-client')],
     loader: 'babel-loader'
});

你好,我这样改还是报错,能分享下您的 配置文件 和 package.json 文件吗

doramart commented 3 years ago

我找到方法了,版本固定下来,重新安装依赖后打包 "swagger-client": "3.5.1",

jiangjunfeng98 commented 3 years ago

同样的错误,设置为fasle是什么意思? 那样不会导致编译后缺少功能吗

不启用swagger插件而已,对内的二次开发没啥大用处。根据实际情况来,也可以根据上面的回复调整配置

121595113 commented 3 years ago

ykit.config.js添加babel-loader可解,希望有人可以提一个pr修复

 baseConfig.module.preLoaders.push({
     test: /\.(js|jsx)$/,
     include: [path.resolve(__dirname, './node_modules/swagger-client')],
     loader: 'babel-loader'
});

你好,我这样改还是报错,能分享下您的 配置文件 和 package.json 文件吗

ykit.config.js 见下文注释

var path = require('path');
var AssetsPlugin = require('assets-webpack-plugin');
var CompressionPlugin = require('compression-webpack-plugin');
var commonLib = require('./common/plugin.js');
var assetsPluginInstance = new AssetsPlugin({
  filename: 'static/prd/assets.js',
  processOutput: function(assets) {
    return 'window.WEBPACK_ASSETS = ' + JSON.stringify(assets);
  }
});
var fs = require('fs');
var package = require('./package.json');
var yapi = require('./server/yapi');
var isWin = require('os').platform() === 'win32'

var compressPlugin = new CompressionPlugin({
  asset: '[path].gz[query]',
  algorithm: 'gzip',
  test: /\.(js|css)$/,
  threshold: 10240,
  minRatio: 0.8
});

function createScript(plugin, pathAlias) {
  let options = plugin.options ? JSON.stringify(plugin.options) : null;
  if (pathAlias === 'node_modules') {
    return `"${plugin.name}" : {module: require('yapi-plugin-${
      plugin.name
    }/client.js'),options: ${options}}`;
  }
  return `"${plugin.name}" : {module: require('${pathAlias}/yapi-plugin-${
    plugin.name
  }/client.js'),options: ${options}}`;
}

function initPlugins(configPlugin) {
  configPlugin = require('../config.json').plugins;
  var systemConfigPlugin = require('./common/config.js').exts;

  var scripts = [];
  if (configPlugin && Array.isArray(configPlugin) && configPlugin.length) {
    configPlugin = commonLib.initPlugins(configPlugin, 'plugin');
    configPlugin.forEach(plugin => {
      if (plugin.client && plugin.enable) {
        scripts.push(createScript(plugin, 'node_modules'));
      }
    });
  }

  systemConfigPlugin = commonLib.initPlugins(systemConfigPlugin, 'ext');
  systemConfigPlugin.forEach(plugin => {
    if (plugin.client && plugin.enable) {
      scripts.push(createScript(plugin, 'exts'));
    }
  });

  scripts = 'module.exports = {' + scripts.join(',') + '}';
  fs.writeFileSync('client/plugin-module.js', scripts);
}

initPlugins();

module.exports = {
  plugins: [
    {
      name: 'antd',
      options: {
        modifyQuery: function(defaultQuery) {
          // 可查看和编辑 defaultQuery
          defaultQuery.plugins = [];
          defaultQuery.plugins.push([
            'transform-runtime',
            {
              polyfill: false,
              regenerator: true
            }
          ]);
          defaultQuery.plugins.push('transform-decorators-legacy');
          defaultQuery.plugins.push(['import', { libraryName: 'antd' }]);
          return defaultQuery;
        },
        exclude: isWin ? /(tui-editor|node_modules\\(?!_?(yapi-plugin|json-schema-editor-visual)))/ : /(tui-editor|node_modules\/(?!_?(yapi-plugin|json-schema-editor-visual)))/
      }
    }
  ],
  devtool: 'cheap-source-map',
  config: function(ykit) {
    return {
      exports: ['./index.js'],
      commonsChunk: {
        vendors: {
          lib: [
            // 'anujs',
            'react',
            'react-dom',
            'redux',
            'redux-promise',
            'react-router',
            'react-router-dom',
            'prop-types',
            'react-dnd-html5-backend',
            'react-dnd',
            'reactabular-table',
            'reactabular-dnd',
            'table-resolver'
          ],
          lib2: ['brace', 'json5', 'url', 'axios'],
          lib3: ['mockjs', 'moment', 'recharts']
        }
      },
      modifyWebpackConfig: function(baseConfig) {
        var ENV_PARAMS = {};
        switch (this.env) {
          case 'local':
            ENV_PARAMS = 'dev';
            break;
          case 'dev':
            ENV_PARAMS = 'dev';
            break;
          case 'prd':
            ENV_PARAMS = 'production';
            break;
          default:
        }

        baseConfig.plugins.push(
          new this.webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(ENV_PARAMS),
            'process.env.version': JSON.stringify(package.version),
            'process.env.versionNotify': yapi.WEBCONFIG.versionNotify
          })
        );

        //初始化配置
        baseConfig.devtool = 'cheap-module-eval-source-map';
        baseConfig.context = path.resolve(__dirname, './client');
        baseConfig.resolve.alias.client = '/client';
        baseConfig.resolve.alias.common = '/common';

        baseConfig.resolve.alias.exts = '/exts';

        // baseConfig.resolve.alias.react = 'anujs';
        // baseConfig.resolve.alias['react-dom'] = 'anujs';

        baseConfig.output.prd.path = 'static/prd';
        baseConfig.output.prd.publicPath = '';
        baseConfig.output.prd.filename = '[name]@[chunkhash][ext]';

        baseConfig.module.noParse = /node_modules\/jsondiffpatch\/public\/build\/.*js/;
        baseConfig.module.loaders.push({
          test: /\.less$/,
          loader: ykit.ExtractTextPlugin.extract(
            require.resolve('style-loader'),
            require.resolve('css-loader') +
              '?sourceMap!' +
              require.resolve('less-loader') +
              '?sourceMap'
          )
        });

        baseConfig.module.loaders.push({
          test: /.(gif|jpg|jpeg|png|woff|woff2|eot|ttf|svg)$/,
          loader: 'url-loader',
          options: {
            limit: 8192,
            name: ['[path][name].[ext]?[sha256#base64:8]']
          }
        });

        baseConfig.module.loaders.push({
          test: /\.(sass|scss)$/,
          loader: ykit.ExtractTextPlugin.extract(
            require.resolve('css-loader') +
              '?sourceMap!' +
              require.resolve('sass-loader') +
              '?sourceMap'
          )
        });

        baseConfig.module.preLoaders.push({
          test: /\.(js|jsx)$/,
          exclude: /tui-editor|node_modules|google-diff.js/,
          loader: 'eslint-loader'
        });
        // @doramart 只是添加了这里的一个配置
        baseConfig.module.preLoaders.push({
          test: /\.(js|jsx)$/,
          include: [path.resolve(__dirname, './node_modules/swagger-client')],
          loader: 'babel-loader'
        });

        baseConfig.module.preLoaders.push({
          test: /\.json$/,
          loader: 'json-loader'
        });

        if (this.env == 'prd') {
          baseConfig.plugins.push(
            new this.webpack.optimize.UglifyJsPlugin({
              compress: {
                warnings: false
              }
            })
          );
          baseConfig.plugins.push(assetsPluginInstance);
          baseConfig.plugins.push(compressPlugin);
          baseConfig.plugins.push(
            new this.webpack.ContextReplacementPlugin(/moment[\\\/]locale$/, /^\.\/(zh-cn|en-gb)$/)
          );
        }
        return baseConfig;
      }
    };
  },
  server: {
    // true/false,默认 false,效果相当于 ykit server --hot
    hot: true,
    // true/false,默认 false,开启后可在当前打开的页面提示打包错误
    overlay: false
  },
  hooks: {},
  commands: []
};

package.json没错任何修改,如下:

{
  "name": "yapi-vendor",
  "version": "1.9.2",
  "description": "YAPI",
  "main": "server/app.js",
  "scripts": {
    "dev-copy-icon": "cp -r static/iconfont ./",
    "dev-server": " nodemon server/app.js dev -L",
    "install-server": " node server/install.js",
    "dev-client": "npm run dev-copy-icon && ykit s -p 4000",
    "dev": "npm run dev-server & npm run dev-client",
    "start": " node server/app.js",
    "test": "ava",
    "build-client": "NODE_ENV=production ykit pack -m",
    "npm-publish": "node ./npm-publish.js",
    "docs": "ydoc build"
  },
  "scripts-info": {
    "start": "运行生产环境服务器",
    "install-server": "初始化数据库数据,用于安装",
    "dev": "运行开发服务器",
    "dev-server": "运行后端开发服务器",
    "dev-client": "运行前端开发服务器",
    "test": "执行测试"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:YMFE/yapi.git"
  },
  "author": "",
  "license": "Apache-2.0",
  "dependencies": {
    "@sentry/react": "^5.20.1",
    "ajv": "^5.5.1",
    "ajv-i18n": "^2.2.0",
    "axios": "0.18.1",
    "compare-versions": "^3.4.0",
    "copy-to-clipboard": "3.0.8",
    "cpu-load": "^1.0.0",
    "crypto-js": "^3.1.9-1",
    "deep-extend": "^0.5.0",
    "deref": "^0.7.3",
    "easy-json-schema": "0.0.2-beta",
    "fs-extra": "^3.0.1",
    "generate-schema": "^2.6.0",
    "immer": "^1.1.1",
    "js-base64": "^2.3.2",
    "json-schema-faker": "^0.5.0-rc16",
    "json-schema-ref-parser": "4.0.0",
    "json5": "0.5.1",
    "jsondiffpatch": "0.3.11",
    "jsonwebtoken": "7.4.1",
    "jsrsasign": "^8.0.12",
    "koa": "2.0.0",
    "koa-body": "^2.5.0",
    "koa-bodyparser": "3.2.0",
    "koa-multer": "1.0.2",
    "koa-mysql-session": "0.0.2",
    "koa-router": "^7.0.1",
    "koa-send": "3.2.0",
    "koa-session-minimal": "3.0.3",
    "koa-static": "3.0.0",
    "koa-websocket": "4.0.0",
    "ldapjs": "^1.0.1",
    "markdown-it": "8.4.0",
    "markdown-it-anchor": "4.0.0",
    "markdown-it-table-of-contents": "0.3.2",
    "md5": "2.2.1",
    "mockjs": "1.0.1-beta3",
    "moment": "^2.19.3",
    "mongodb": "3.1.8",
    "mongoose": "5.7.5",
    "mongoose-auto-increment": "5.0.1",
    "moox": "^1.0.2",
    "node-schedule": "^1.3.2",
    "nodemailer": "4.0.1",
    "os": "0.1.1",
    "qs": "^6.7.0",
    "request": "2.81.0",
    "sha.js": "2.4.9",
    "sha1": "1.1.1",
    "swagger-client": "^3.5.1",
    "tslib": "1.8.0",
    "underscore": "1.8.3",
    "url": "0.11.0",
    "vm2": "^3.8.4",
    "yapi-plugin-qsso": "^1.1.0"
  },
  "devDependencies": {
    "antd": "3.2.2",
    "anujs": "^1.2.6",
    "assets-webpack-plugin": "^3.5.1",
    "ava": "^0.22.0",
    "babel": "^6.5.2",
    "babel-core": "^6.8.0",
    "babel-eslint": "^7.2.3",
    "babel-loader": "^6.2.4",
    "babel-plugin-import": "^1.3.1",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-object-rest-spread": "^6.8.0",
    "babel-plugin-transform-runtime": "^6.9.0",
    "babel-plugin-webpack-alias": "^2.1.2",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-stage-3": "^6.24.1",
    "babel-register": "^6.9.0",
    "babel-runtime": "^6.9.2",
    "brace": "^0.10.0",
    "buffer-shims": "^1.0.0",
    "compression-webpack-plugin": "^1.0.0",
    "copy-webpack-plugin": "^4.0.1",
    "core-decorators": "^0.17.0",
    "css-loader": "^0.28.4",
    "eslint": "^3.19.0",
    "eslint-loader": "^1.9.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-react": "^7.1.0",
    "extract-text-webpack-plugin": "2.0.0",
    "ghooks": "^2.0.0",
    "happypack": "^4.0.0-beta.5",
    "json-schema-editor-visual": "^1.0.23",
    "less": "^2.7.2",
    "less-loader": "^4.0.5",
    "markdown-it-include": "^1.0.0",
    "node-sass": "^4.9.0",
    "nodemon": "^1.11.0",
    "prop-types": "^15.5.10",
    "rc-queue-anim": "^1.2.0",
    "rc-scroll-anim": "^1.0.7",
    "rc-tween-one": "^1.5.5",
    "react": "^16.2.0",
    "react-dnd": "^2.5.1",
    "react-dnd-html5-backend": "^2.5.1",
    "react-dom": "^16.2.0",
    "react-redux": "^5.0.5",
    "react-router-dom": "^4.1.1",
    "react-scripts": "1.0.10",
    "reactabular-dnd": "^8.9.0",
    "reactabular-table": "^8.9.0",
    "recharts": "^1.0.0-beta.0",
    "redux": "^3.7.1",
    "redux-devtools": "^3.4.0",
    "redux-devtools-dock-monitor": "^1.1.2",
    "redux-devtools-log-monitor": "^1.3.0",
    "redux-promise": "^0.5.3",
    "rewire": "^2.5.2",
    "sass-loader": "^7.0.3",
    "string-replace-webpack-plugin": "^0.1.3",
    "style-loader": "^0.18.2",
    "table-resolver": "^3.2.0",
    "validate-commit-msg": "^2.12.2",
    "webpack": "^2.2.0",
    "webpack-dev-middleware": "^1.12.0",
    "webpack-node-externals": "^1.6.0",
    "ydoc-plugin-img-view": "^1.0.1",
    "ykit": "0.6.2",
    "ykit-config-antd": "0.1.3",
    "ykit-config-es6": "^1.1.0"
  },
  "config": {
    "ghooks": {
      "commit-msg": "npx validate-commit-msg"
    },
    "validate-commit-msg": {
      "types": [
        "feat",
        "fix",
        "docs",
        "test",
        "chore",
        "refactor",
        "opti"
      ],
      "warnOnFail": false,
      "maxSubjectLength": 100,
      "subjectPattern": ".+",
      "subjectPatternErrorMsg": "请输入message信息!",
      "helpMessage": "Commit message 格式错误, http://www.ruanyifeng.com/blog/2016/01/commit_message_change_log.html"
    }
  },
  "engines": {
    "node": ">= 7.6.0",
    "npm": ">= 4.1.2"
  },
  "babel": {
    "presets": [
      [
        "es2015",
        {
          "loose": true,
          "modules": "commonjs"
        }
      ],
      "es2017",
      "stage-0",
      "react"
    ],
    "plugins": [
      "transform-runtime",
      [
        "webpack-alias",
        {
          "config": "webpack.alias.js"
        }
      ]
    ]
  },
  "ava": {
    "files": [
      "test/**/*.js"
    ],
    "require": [
      "babel-register"
    ],
    "babel": "inherit"
  }
}
BEWINDOWEB commented 3 years ago

我找到方法了,版本固定下来,重新安装依赖后打包 "swagger-client": "3.5.1",

二次开发遇到同样的问题,用固定版本号这个方法后就OK了。 另外,如果不解决这个问题,在“数据管理”的Tab页面,会白屏(因为swagger插件没有正确加载)。

blackkeai commented 3 years ago

我找到方法了,版本固定下来,重新安装依赖后打包 "swagger-client": "3.5.1",

你好,这个版本我看源码的package.json 里面本来就是这个版本呀?

AsherSun commented 3 years ago

我找到方法了,版本固定下来,重新安装依赖后打包 "swagger-client": "3.5.1",

你好,这个版本我看源码的package.json 里面本来就是这个版本呀?

package.json 中看虽然是3.5.1. 但是安装的有可能是最新版本的。所以需要看下package-lock.json 或者 yarn.lockswagger-client版本。如果不是3.5.1,就固定下版本吧

zz215 commented 2 years ago

我找到方法了,版本固定下来,重新安装依赖后打包 "swagger-client": "3.5.1",

二次开发遇到同样的问题,用固定版本号这个方法后就OK了。 另外,如果不解决这个问题,在“数据管理”的Tab页面,会白屏(因为swagger插件没有正确加载)。

数据管理页面白屏问题找了几个小时解决方案,在您的指导下解决了,非常感谢~!

dptong commented 1 year ago

我找到方法了,版本固定下来,重新安装依赖后打包 "swagger-client": "3.5.1",

你好,这个版本我看源码的package.json 里面本来就是这个版本呀?

package.json 中看虽然是3.5.1. 但是安装的有可能是最新版本的。所以需要看下package-lock.json 或者 yarn.lockswagger-client版本。如果不是3.5.1,就固定下版本吧

必须用这个版本吗