导入本地打字稿包未解决

Top*_*psy 6 importerror typescript nestjs

这就是我想要实现的目标。

我想制作一个包,用于共享打字稿接口,或在我的前端(react)和后端(nestjs)之间共享的通用配置

我创建了名为“shared”的项目,并在我的 package.json 中创建了一个链接。

就像这样:"shared": "file:../shared",

我的 React 效果很好,可以使用我的界面或“共享”中的任何内容,没有任何错误!

我在nestjs项目中做了同样的事情,编辑器中没有错误,我可以在node_modules中看到共享包。但是当我编译该项目时,它失败了:

错误:找不到模块“共享/接口/用户”

所以我猜问题出在我的nestjsconf或webpack中的某些东西......但我不知道是什么。

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "moduleResolution": "node",
  },
}
Run Code Online (Sandbox Code Playgroud)

webpack-hmr.config.js

const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
const { RunScriptWebpackPlugin } = require('run-script-webpack-plugin');

module.exports = function (options) {

    return {
        ...options,
        entry: ['webpack/hot/poll?500', options.entry],
        watch: true,
        externals: [
            nodeExternals({
                allowlist: ['webpack/hot/poll?500'],
            }),
        ],
        plugins: [
            ...options.plugins,
            new webpack.HotModuleReplacementPlugin(),
            new RunScriptWebpackPlugin({ name: options.output.filename }),
            new webpack.WatchIgnorePlugin( {paths: [/\.js$/, /\.d\.ts$/] }),

        ],
        
    };
};
Run Code Online (Sandbox Code Playgroud)

如果您有任何想法:)谢谢大家!

Fla*_*ken 1

您还应该显示导入模块的代码。该问题可能是由于导入引起的,其中路径应该是相对于您的文件的路径,而不是绝对路径。相同:https ://stackoverflow.com/a/54049216/532695

如果您确实想要更短的链接,例如import {myInterface} from @shared/myModule可以在tsconfig.json文件中设置路径别名。

{
...
  "compilerOptions": {
    "paths": {
      "@shared/*": ["path/to/shared/folder/*"],
    }
  },
...
}
Run Code Online (Sandbox Code Playgroud)

但这只能被 ts 或可能 ts-node 理解。如果您使用 webpack 编译它,您可能还需要在其配置中创建一个别名:

...
resolve: {
  alias: {
    shared: path.resolve(__dirname,'path/to/shared/folder/')
  }
}
...
Run Code Online (Sandbox Code Playgroud)

这是一篇关于如何为 webpack 设置别名的文章