React.Импорт SVG - PullRequest
       2

React.Импорт SVG

0 голосов
/ 17 октября 2018

Экспорт SVG из корневого файла index.ts

import * as upArrow from "./up-arrow.svg";
import * as downArrow from "./down-arrow.svg";

export { upArrow, downArrow };

Попробуйте использовать в моем компоненте

import * as React from "react";
import { Icon } from "components";
import { upArrow, downArrow } from "common/assets";

const CollapseIcon = ({ condition }) => (
  <Icon alternative={upArrow} asset={downArrow} condition={condition} />
);

export default CollapseIcon;

Если это важно, я использую значения asset и alternative в атрибуте src как этот

export default styled.img.attrs<IconProps>({
  src: ({ condition, alternative, asset }: IconProps) =>
    condition ? alternative : asset,
  alt: ({ alt }: IconProps) => alt
})`
  vertical-align: middle;
 `

Но получите html-элемент с двойными кавычками.Если удалить его, вид элемента корректно.Где я не прав?

enter image description here

Я пытаюсь объявить активы без кода согласно документам , но никогда не меняется

declare module "*.svg" {
  const content: string;
  export default content;
}
declare module "*.png";
declare module "*.jpg";

Моя конфигурация Webpack:

"use strict";

const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CaseSensitivePathsPlugin = require("case-sensitive-paths-webpack-plugin");
const InterpolateHtmlPlugin = require("react-dev-utils/InterpolateHtmlPlugin");
const WatchMissingNodeModulesPlugin = require("react-dev-utils/WatchMissingNodeModulesPlugin");
const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const getClientEnvironment = require("./env");
const paths = require("./paths");

const publicPath = "/";
const publicUrl = "";
const env = getClientEnvironment(publicUrl);

module.exports = {
  devtool: "cheap-module-source-map",
  entry: [
    require.resolve("./polyfills"),
    require.resolve("react-dev-utils/webpackHotDevClient"),
    paths.appIndexJs
  ],
  output: {
    pathinfo: true,
    filename: "static/js/bundle.js",
    chunkFilename: "static/js/[name].chunk.js",
    publicPath: publicPath,
    devtoolModuleFilenameTemplate: info =>
      path.resolve(info.absoluteResourcePath).replace(/\\/g, "/")
  },
  resolve: {
    modules: [paths.appSrc, paths.appNodeModules].concat(
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),
    extensions: [".ts", ".tsx", ".js", ".jsx"],
    alias: {
      "react-native": "react-native-web"
    },
    plugins: [
      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson])
    ]
  },
  module: {
    strictExportPresence: true,
    rules: [
      {
        enforce: "pre",
        test: /\.js$/,
        loader: "source-map-loader"
      },
      {
        oneOf: [
          {
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
            loader: require.resolve("url-loader"),
            options: {
              limit: 10000,
              name: "static/media/[name].[hash:8].[ext]"
            }
          },
          {
            test: /\.(ts|tsx|js|jsx)?$/,
            loader: "awesome-typescript-loader",
            options: {
              getCustomTransformers: require("../config/transformers.js")
            }
          },
          {
            exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
            loader: require.resolve("file-loader"),
            options: {
              name: "static/media/[name].[hash:8].[ext]"
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new InterpolateHtmlPlugin(env.raw),
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml
    }),
    new webpack.NamedModulesPlugin(),
    new webpack.DefinePlugin(env.stringified),
    new webpack.HotModuleReplacementPlugin(),
    new CaseSensitivePathsPlugin(),
    new WatchMissingNodeModulesPlugin(paths.appNodeModules),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
  ],
  node: {
    dgram: "empty",
    fs: "empty",
    net: "empty",
    tls: "empty",
    child_process: "empty"
  },
  performance: {
    hints: false
  },
  externals: {
    react: "React",
    "react-dom": "ReactDOM"
  },
  devtool: "source-map"
};

UPD.Как я вижу, браузер получает мою строку в виде ссылки

enter image description here

1 Ответ

0 голосов
/ 18 октября 2018

Добавить .svg расширение к списку расширений для url-loader вот так

...
rules: [
...
          {
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/, /\.svg$/],
            loader: require.resolve("url-loader"),
            options: {
              limit: 10000,
              name: "static/media/[name].[hash:8].[ext]"
            }
          },
...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...