本地包的节点路径解析

时间:2019-11-04 17:15:42

标签: node.js reactjs typescript webpack

我具有以下文件夹结构。

.
├── client
│   ├── components
│   ├── dev.server.ts
│   ├── features
│   ├── index.html
│   ├── index.tsx
│   ├── package.json
│   ├── tsconfig.json
│   ├── webpack.config.ts
│   └── webpack.dev.config.ts
├── dev.server.ts
├── package.json
├── prod.server.ts
├── server
│   ├── core
│   ├── models
│   ├── node_modules
│   ├── package.json
│   ├── routes
│   ├── server.module.ts
└── tsconfig.json

在根文件夹的dev.server.ts中,我将clientserver文件夹作为模块导入,我将其添加到主package.json中,如下所示:

"dependencies": {
    "client": "./client",
    "server": "./server"
  }

server 运行得很好。但是client遇到了问题。当我尝试使用webpack启动Dev服务器时,它无法解析node_modules中的软件包。它尝试在根目录(而不是脚本的位置)上找到它们。

ERROR in multi react-hot-loader/patch ./client/index.tsx webpack-hot-middleware/client
Module not found: Error: Can't resolve 'webpack-hot-middleware/client' in '/home/victor/Dev/back'
 @ multi react-hot-loader/patch ./client/index.tsx webpack-hot-middleware/client main[2]

我能够通过将process.chdir(path.resolve(__dirname))添加到客户端的dev.server.ts脚本的开头来使其工作,我知道这是理想的选择。这里是它的内容:

// ./client/dev.server.ts
import webpackConfig from './webpack.dev.config';
import path from 'path';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';

const CustomMiddlewares = () => {
  // This line makes it work
  process.chdir(path.resolve(__dirname));
  // Configure o compilador
  let conf = webpackConfig();
  let compiler = webpack(conf);
  let devMiddleware = webpackDevMiddleware(compiler, { publicPath: '/', logLevel: "error" });
  let hotMiddleware = webpackHotMiddleware(compiler);

  return [devMiddleware, hotMiddleware];
}
export default CustomMiddlewares;

并像这样使用它:

// ./dev.server.ts
import clientDevServer from 'client';
import startServer from 'server';

const startDevServer = async () => {
  let app = await startServer();

  // 
  let [devMiddleware, hotMiddleware] = clientDevServer();
  // Serviço de middleware
  app.use(devMiddleware);

  // hotReload
  app.use(hotMiddleware);
}

startDevServer();

如何让我的webpack脚本尝试使用客户端的node_modules文件夹而不是父文件夹的路径来解析文件?

0 个答案:

没有答案