子目录中的Webpack-dev-server - 不编译&没有热重装

时间:2017-05-19 11:58:14

标签: reactjs webpack webpack-dev-server

我试图在子目录(公共)中运行webpack dev服务器,以便我可以将反应集成到现有站点中。

Repo - minimal-react-webpack-starter

当我从子目录运行它时,使用npm run start,热重新加载或编译都不起作用,但是当我从root运行它们而没有--content-basedevServer.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 个答案:

答案 0 :(得分: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的官方文档here

我希望这有帮助!