在 Node.js 和 Vue.js 之间共享 TypeScript 代码

时间:2021-07-07 15:14:27

标签: javascript node.js typescript vue.js

我很难弄清楚如何做到这一点。我的环境是:

  • Node.js 16.1.x
  • Vue.js 3.x
  • TypeScript 4.2.4

我的目录结构是这样的:

  • Root(Node.js 服务器)
    • 共享
      • MySharedFile.ts
    • ui(Vue.js 代码)

MySharedFile.ts 正在导出一个非常简单的模块:

export const MyShared = {
  TEST: 1
};

在 Vue.js 中,我尝试导入此模块 import {MyShared} from '../../shared/MySharedFile',但是在构建应用程序时,我收到错误 Parsing error: 'import' and 'export' may appear only with 'sourceType: module'。我搜索并发现 a thread 建议更改 eslintrc 设置,但没有用。这个错误对我来说真的没有意义,那么它是什么意思,我该如何解决?

ui/tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "outDir": "./dist",
    // https://github.com/TypeStrong/ts-loader/issues/1138
    "importsNotUsedAsValues": "preserve",
    "types": [
      "webpack-env"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "es2020",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

ui/.eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    '@vue/typescript',
    'plugin:vue/vue3-recommended',
    'plugin:vue/vue3-essential',
    'eslint:recommended',
    '@vue/typescript/recommended'
  ],
  parserOptions: {
    ecmaVersion: 11,
    sourceType: 'module',
    allowImportExportEverywhere: true
  }
}

对于想要 source code 的任何人...我现在遇到了一个新错误解析错误:'import' 和 'export' 可能只出现在 'sourceType: module'< /p>

1 个答案:

答案 0 :(得分:0)

我从中学到了一些东西。首先是我使用了所谓的 monorepo。第二个是我应该使用某种工作空间,我最终使用了 npm workspaces,但还有其他选项,例如 yarn workspaces。我不得不重构我的应用程序以遵循不同的结构,所以我现在有这样的东西:

  • Root(主工作区)
    • api (Node.js)
      • package.json ("dependencies": {"shared": "^1.0.0"})
      • tsconfig.json
      • package-lock.json(已删除)
    • 共享(TypeScript 代码)
      • package.json ("version": "1.0.0")
      • tsconfig.json
    • ui (Vue.js)
      • package.json ("dependencies": {"shared": "^1.0.0"})
      • tsconfig.json
      • package-lock.json(已删除)
    • package.json ("workspaces": ["api", "shared", "ui"])
    • package-lock.json(生成并包含工作区的所有 deps)

移动到这个结构后,我不必修改 tsconfig.jsonvue.config.js 文件来添加 shared 目录,因为我可以在导入时像任何其他包一样引用它.我也喜欢这种方法,因为它将我所有的 node_modules 保存在主工作区级别的一个目录中。