reactjs - 如何在 Webpack 配置中使用 __webpack_public_path__ 变量?

标签 reactjs typescript webpack typescript2.0

我目前正在使用 React、TypeScript 和 Webpack 开发 Web 应用程序。我希望 Webpack 根据我只在运行时而不是在编译时知道的子域生成图像 URL。

我在 Webpacks 的文档中读到过这个: http://webpack.github.io/docs/configuration.html#output-publicpath

Note: In cases when the eventual publicPath of of output files isn’t known at compile time, it can be left blank and set dynamically at runtime in the entry point file. If you don’t know the publicPath while compiling you can omit it and set webpack_public_path on your entry point.

webpack_public_path = myRuntimePublicPath

// rest of your application entry

但我无法让它工作。

我已经在我的应用程序入口点设置了 webpack_public_path 变量。但是我怎样才能在我的 Webpack 配置中使用它的值呢? 我需要在这里使用它:

"module": { "rules": [ { "test": /.(png|jpg|gif)(\?[\s\S]+)?$/, "loaders": [url?limit=8192&name=/images/[hash].[ext]] } ] }

我需要做这样的事情:

"loaders": ['url?limit=8192&name=__webpack_public_path__/images/[hash].[ext]']

回答

我已经设法让它工作了。因此,在我的入口点文件 (start.tsx) 中,我在导入之前声明了 de __webpack_public_path__ free var,并在导入之后为其赋值。

/// <reference path="./definitions/definitions.d.ts" />
declare let __webpack_public_path__;

import './styles/main.scss';

/* tslint:disable:no-unused-variable */
import * as React from 'react';
/* tslint:enable:no-unused-variable */
import * as ReactDOM from 'react-dom';
import * as Redux from 'redux';
import { Root } from './components/root';

__webpack_public_path__ = `/xxxx/dist/`;

现在,当我有一个 img 标签时,正在使用公共(public)路径:

<img src={require('../../images/logo.png')} />

变成:

<img src='/xxxx/dist/images/125665qsd64134fqsf.png')} />

最佳答案

这是我生成的 HTML 的基本设置:

<script>
    window.resourceBaseUrl = 'server-generated-path';
</script>
<script src="path-to-bundle" charset="utf-8"></script>

我的主要入口点脚本:

__webpack_public_path__ = window.resourceBaseUrl;

关于reactjs - 如何在 Webpack 配置中使用 __webpack_public_path__ 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40661251/

相关文章:

javascript - 没有 JSX 的条件渲染

javascript - 在 localStorage 中存储对象

javascript - 输入类型文件 - 如何访问文件属性?

.net - 在 AspNet Core 中调试 ReactJS 组件

javascript - 为什么我们在使用 babel-loader 时要排除 node_modules?

Webpack 内存不足

javascript - 按错误对象集合中值为 true 的属性过滤

css - 在 React 中动画 div(进入和退出)

reactjs - <Query> 与 graphql Hoc 这是在 React apollo 中将 graphql 查询与组件 Hook 的最佳方式

javascript - 如何限制在 ngFor 中显示的项目数量?