React router v3.0 配置根目录basename

最近在react项目中遇到路由需要配置根目录路径问题,查了很多资料,最后终于解决了,记录一下,希望对React学习的人有帮助。

问题描述:

使用react框架创建项目时,使用react-router ,运行npm run dev 后,使用http://localhost:8080/home 即可访问首页。但真实情况下我们打包后放在后端的前端代码都会使用nginx配置,配置后访问的路径会带一个项目名称。如http://192.168.1.6/project/home。此时这样访问的时候就需要在react框架内的router路由配置basename,为每个路由添加和nginx配置的项目名一样的根目录。本例中即为/project。

解决方法:

1.安装history
npm install [email protected] --save
2.webpack 配置全局根目录名称,pulgin结点下添加:

  • 打开webpack.build.config.js 文件,添加如下:
new webpack.DefinePlugin({
          BASENAME: JSON.stringify('/project')
        })
  • 打开webpack.develop.config.js 文件,添加如下:
 new webpack.DefinePlugin({
          BASENAME: JSON.stringify('/')
        })
3. 在全局配置app.js中配置如下:
import {Router,useRouterHistory,browserHistory} from 'react-router';
import {syncHistoryWithStore} from 'react-router-redux';
import {createHistory } from 'history';
...
//如果是开发环境就是用browserHistory,如果是build环境,则添加根目录BASENAME
let baseHistory = browserHistory;
if(BASENAME !== '/') {
    baseHistory = useRouterHistory(createHistory)({
        basename: BASENAME
    });
}

const store = configureStore(initialState, baseHistory);

//同步历史路由和Store
const history = syncHistoryWithStore(baseHistory, store, {
    selectLocationState: makeSelectLocationState(),
});
...
//引用history
<Provider store={store}>
        <Router
            history={history}
            routes={rootRoute}
        />
    </Provider>
//修改全局browserHistory,
//如果是开发环境就是用browserHistory,如果是build环境,则是用包装后的history
window.browserHistory = baseHistory;

其他页面跳转路由时调用:

window.browserHistory.push('/home');                    //切换页面

总结:通过以上步骤即完成了路由根目录的配置,如在生产环境运行,则会自动跳转至:http://192.168.1.6/project/home 地址。

后续

虽然basename 配置成功,路由全部跳转成功,但是发现原来打包的图片资源也会有目录不一致的情况。图片资源路径不一致的情况有两种解决方法:
1.仔细检查资源配置路径,不能使用绝对路径(如‘/img/a.png’),一定要用相对路径(如:‘img/a.png’ 或'../img/a.png')。
2.在相对路径没有问题的时候,使用 url-loader 插件加载图片资源。
~安装url-loader
npm install [email protected] --save
~ 分别在webpack.build.config.js 和webpack.develop.config.js 中,添加使用:
{
   test: /\.(png|jpg)$/,
   loader: 'url-loader?limit=8192&name=images/[hash:8].[name].[ext]',
      exclude: [nodeModulesPath],             //不解析node_modules目录的es6语法
}
至此,针对路由添加根目录的问题就讲到这里,欢迎大家留言讨论!




猜你喜欢

转载自blog.csdn.net/allence_z/article/details/80949436