子目录中的 Webpack-dev-server - 不编译和不热重载

IT技术 reactjs webpack webpack-dev-server
2021-05-10 02:58:56

我正在尝试在子目录(公共)中运行 webpack 开发服务器,以便我可以将 react 集成到现有站点中。

回购-minimal-react-webpack-starter

当我从子目录运行它时,使用npm run start,热重载或编译都不起作用,但是当我从根目录运行它们时,--content-base或者devServer.publicPath它工作正常。

文件夹结构 -

|- App/
    |- node-modules/
    |- public/
        |- react/
            |- main.js
        |- index.html
    |- shared/
        |- react/
            |- components/
            |- main.js
|- package.json
|- webpack.config.js

index.html 包含 <script src="react/main.js"></script>

Webpack 配置 -

const path = require('path');

const config = {
    entry: './shared/react/main.js',
    output: {
        publicPath: "public/react",
        path: path.resolve(__dirname, 'public/react'),
        filename: 'main.js',
    },
    module: {
        loaders: [
            { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
            { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ }
        ]
    },
    devServer: {
            inline: true,
             publicPath: "public/",
             contentBase: path.join(__dirname, "public"),
             hot: true,
             port: 8080,
        },

}

pacakge.json -

{
"name": "App",
"version": "1.0.0",
"repository": "Ash-repo",
"description": "App",
"devDependencies": {
  "babel-core": "^6.24.1",
  "babel-loader": "^7.0.0",
  "babel-preset-es2015": "^6.24.1",
  "babel-preset-react": "^6.24.1",
  "path": "^0.12.7",
  "react": "^15.5.4",
  "react-dom": "^15.5.4",
  "webpack": "^2.5.0",
  "webpack-dev-server": "^2.4.5"
},
"scripts": {
  "start": "webpack-dev-server --content-base public/ --hot --progress --colors",
  "watch": "webpack --progress --colors --watch",
  "test": "echo \"Error: no test specified\" && exit 1"
}
}

不知道为什么它不编译或重新加载,我已经设置publicPath(在输出和 devServer 中)并content-base指向公共。我看了一下http://localhost:8080/webpack-dev-server/http://localhost:8080/但没有重新加载或编译发生!

任何帮助将不胜感激!👍

1个回答

webpack 配置似乎不正确。使用下面的 webpack 配置将在子目录的情况下启用热重载。

const path = require('path');
const config = {
    entry: './shared/react/main.js',
    output: {
        publicPath: "public/react",
        path: path.resolve(__dirname, 'public/react'),
        filename: 'main.js',
    },
    module: {
        loaders: [
            { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
            { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ }
        ]
    },
    devServer: {
        inline: true,
        publicPath: "/react/",
        contentBase: path.join(__dirname, "public"),
        hot: true,
        port: 8070
    }
}

devServer.publicPath是这里的重要更改。有关它的更多信息,请在此处访问 webpack 的官方文档

我希望这有帮助!