使用 yarn 工作区时 Webpack 开发服务器出错

Jer*_*me 8 webpack-dev-server yarnpkg yarn-workspaces

webpack-dev-server error cannot find module 'webpack-cli/bin/config/config-yargs在 yarn 工作区中安装 webpack、webpack-cli 和 webpack-dev-server 时出现错误“ '”。在 repo 中安装它们时没有这个问题。

我检查了根节点和子节点中的 node_modules。看来这个 config/config-yargs 文件安装在CHILD的 node_module 中,但没有安装在ROOT 中

我必须手动将它从子级复制到根目录才能使其正常工作。

有没有办法正确安装它?

我的根 package.json :

{
    "private": true,
    "workspaces": [
        "packages/server",
        "packages/front", <-- webpack has been installed her
    ],
    "name": "test",
    "version": "1.0.0",
    "main": "index.js",
    "license": "MIT"
}
Run Code Online (Sandbox Code Playgroud)

子 package.json 的一部分

{
"devDependencies": {
        "@babel/core": "^7.8.4",
        "@babel/preset-env": "^7.8.4",
        "@babel/preset-react": "^7.8.3",
        "@babel/preset-typescript": "^7.8.3",
        "typescript": "^3.7.5",
        "webpack": "^4.41.6",
        "webpack-cli": "^3.3.11",
        "webpack-dev-server": "^3.10.3"
}
Run Code Online (Sandbox Code Playgroud)

webpack.config.js

const path = require("path");
const rules = [
    {
        test: /\.(tsx)$/,
        exclude: /node_modules/,
        loader: "babel-loader",
    },
    {
        test: /\.css$/,
        loader: ["style-loader", "css-loader"],
    },
];
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    target: "web",
    mode: "development",
    entry: "./src/examples/index.tsx",
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "bundle.js",
    },
    module: { rules },
    resolve: {
        extensions: [".ts", ".tsx", ".js"],
    },
    devServer: {
        contentBase: "./",
        port: 5000,
        historyApiFallback: true, 
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: "react typescript babel webpack boilerplate",
            template: "index.html",
        }),
    ],
};
Run Code Online (Sandbox Code Playgroud)

dav*_*tar 0

解决方案是使用带webpack serve命令的嵌入式 devServer,请在此处阅读

https://webpack.js.org/guides/development/#using-webpack-dev-server

您可能会遇到工作空间的另一个问题,解决方案是nohoist,请在此处阅读相关内容

https://classic.yarnpkg.com/blog/2018/02/15/nohoist/

Nohoist 对我来说不起作用,直到我发现它应该在root package.json上使用而不是在 child 上使用,这是对我有用的版本

"workspaces": {
"packages": [
  "package-1",
  "package-2",
],
"nohoist": [
  "**/webpack",
  "**/webpack/**",
  "**/webpack-dev-server",
  "**/webpack-dev-server/**",
  "**/@webpack-cli",
  "**/@webpack-cli/**",
  "**/webpack-cli",
  "**/webpack-cli/**"
]
},
Run Code Online (Sandbox Code Playgroud)

您可能还想像往常一样删除node_modules :)