Programming

모든 경로에 대해 index.html을 제공하도록 webpack dev 서버에 지시하는 방법

procodes 2020. 7. 19. 17:22
반응형

모든 경로에 대해 index.html을 제공하도록 webpack dev 서버에 지시하는 방법


반응 라우터는 반응 앱이 처리 할 수 ​​있도록 /arbitrary/route합니다. 이것이 작동하려면 일치하는 경로에서 React 앱을 보내려면 서버가 필요합니다.

그러나 webpack dev 서버 는 임의의 엔드 포인트를 처리하지 않습니다.

추가 Express 서버를 사용하는 솔루션이 있습니다. webpack-dev-server가 반응 라우터의 진입 점을 허용하도록 허용하는 방법

그러나 경로 일치를 허용하기 위해 다른 급행 서버를 시작하고 싶지 않습니다. 나는 단지 어떤 URL 과도 일치하도록 webpack dev 서버에 알리고 내 반응 앱을 보내려고합니다. 부디.


작은 구성을 포함하는 가장 쉬운 솔루션을 찾았습니다.

  devServer: {
    port: 3000,
    historyApiFallback: {
      index: 'index.html'
    }
  }

PUSHSTATE WITH WEBPACK-DEV-SERVER 방문하여 이것을 발견했습니다 .


webpack -dev-server 공식 문서의 historyApiFallback 옵션은다음 중 하나를 사용하여 달성 할 수있는 방법을 명확하게 설명합니다.

historyApiFallback: true

경로를 찾지 못하면 index.html로 돌아갑니다.

또는

// output.publicPath: '/foo-app/'
historyApiFallback: {
  index: '/foo-app/'
}

이렇게 나를 위해 작동

devServer: {
    contentBase: "./src",
    hot: true,
    port: 3000,
    historyApiFallback: true

},

폭동 앱 작업


ng eject 명령을 실행 한 후 webpack 및 'eject'옵션과 함께 각도 CLI를 사용하고 있기 때문에 상황이 조금 다릅니다 . package.json에서 'npm start'에 대해 추출 된 npm 스크립트를 수정하여 --history-api-fallback 플래그를 전달했습니다.

"start": "webpack-dev-server --port = 4200 --history-api-fallback "

"scripts": {
"ng": "ng",
"start": "webpack-dev-server --port=4200 --history-api-fallback",
"build": "webpack",
"test": "karma start ./karma.conf.js",
"lint": "ng lint",
"e2e": "protractor ./protractor.conf.js",
"prepree2e": "npm start",
"pree2e": "webdriver-manager update --standalone false --gecko false --quiet",
"startold": "webpack-dev-server --inline --progress --port 8080",
"testold": "karma start",
"buildold": "rimraf dist && webpack --config config/webpack.prod.js --progress --profile --bail"},

설정에 공개 경로를 추가하면 서브 루트를 사용하는 /경우에도 웹팩이 실제 루트 ( ) 를 이해하는 데 도움 이됩니다./article/uuid

따라서 웹팩 구성을 수정하고 다음을 추가하십시오.

output: {
    publicPath: "/"
}

devServer: {
    historyApiFallback: true
}

publicPath리소스가 없으면 제대로로드되지 않을 수 있으며 index.html 만 있습니다.

Webpack에서 테스트 4.6

구성의 더 큰 부분 (더 나은 그림을 얻기 위해) :

entry: "./main.js",
output: {
  publicPath: "/",
  path: path.join(__dirname, "public"),
  filename: "bundle-[hash].js"
},
devServer: {
  host: "domain.local",
  https: true,
  port: 123,
  hot: true,
  contentBase: "./public",
  inline: true,
  disableHostCheck: true,
  historyApiFallback: true
}

를 사용하기로 선택한 경우 webpack-dev-server전체 React 앱을 제공하는 데 사용해서는 안됩니다. bundle.js정적 종속성뿐만 아니라 파일 을 제공하는 데 사용해야합니다 . 이 경우 실제로 경로를 처리하고 HTML을 제공하는 Node.js 진입 점용 서버와 번들 및 정적 리소스 용 서버를 각각 2 대씩 시작해야합니다.

If you really want a single server, you have to stop using the webpack-dev-server and start using the webpack-dev-middleware within your app-server. It will process bundles "on the fly" (I think it supports caching and hot module replacements) and make sure your calls to bundle.js are always up to date.


You can enable historyApiFallback to serve the index.html instead of an 404 error when no other resource has been found at this location.

let devServer = new WebpackDevServer(compiler, {
    historyApiFallback: true,
});

If you want to serve different files for different URIs, you can add basic rewriting rules to this option. The index.html will still be served for other paths.

let devServer = new WebpackDevServer(compiler, {
    historyApiFallback: {
        rewrites: [
            { from: /^\/page1/, to: '/page1.html' },
            { from: /^\/page2/, to: '/page2.html' },
            { from: /^\/page3/, to: '/page3.html' },
        ]
    },
});

I know this question is for webpack-dev-server, but for anyone who uses webpack-serve 2.0. with webpack 4.16.5; webpack-serve allows add-ons.You'll need to create serve.config.js:

const serve = require('webpack-serve');
const argv = {};
const config = require('./webpack.config.js');

const history = require('connect-history-api-fallback');
const convert = require('koa-connect');

serve(argv, { config }).then((result) => {
  server.on('listening', ({ server, options }) => {
      options.add: (app, middleware, options) => {

          // HistoryApiFallback
          const historyOptions = {
              // ... configure options
          };

          app.use(convert(history(historyOptions)));
      }
  });
});

Reference

You will need to change the dev script from webpack-serve to node serve.config.js.


For me I had dots "." in my path e.g. /orgs.csv so I had to put this in my webpack confg.

devServer: {
  historyApiFallback: {
    disableDotRule: true,
  },
},

참고URL : https://stackoverflow.com/questions/31945763/how-to-tell-webpack-dev-server-to-serve-index-html-for-any-route

반응형