使用React在Webpack中加载SVG(@ svgr / webpack)

时间:2019-06-24 09:40:18

标签: reactjs svg webpack sass ssr

Webpack配置:

1-对于.svg,我使用配置:{ test: /\.svg$/, use: ['@svgr/webpack'] }

2- for .scss是使用配置: { test: /\.(sc|sa)ss$/, exclude: /\.module\.(scss|sass)$/, use: [{ loader: MiniCssExtractPlugin.loader, options: { hmr: isEnvDevelopment } }, { loader: require.resolve('css-loader'), options: { modules: true, localIdentName: '[name]__[local]--[hash:base64:5]', importLoaders: 2 } }, { loader: require.resolve('postcss-loader'), options: { ident: 'postcss' } }, { loader: require.resolve("sass-loader") } ] }

  

我在代码中以这种方式使用svgr:

import Ipad from '../../../assets/icons/music_ipod.svg'
...
<div>messages
 <Ipad />
</div>

问题

问题是当我开始执行该项目时遇到以下错误:

\client\assets\icons\music_ipod.svg:1
(function (exports, require, module, __filename, __dirname) { <svg version="1.1" id="Layer_1" x="0px" y="0px"                                                              ^

SyntaxError: Unexpected token <
    at new Script (vm.js:79:7)    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:657:28)    at Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Object.newLoader [as .js] (D:\WebSite_Learn\ReactJs\00--Studied--\Server Side Rendering with React and Redux\Project\MicroServices\Management\node_modules\pirates\lib\index.js:104:7)    at Module.load (internal/modules/cjs/loader.js:599:32)
Side Rendering with React and Redux\Project\MicroServices\Management\client\components\layout\header/index.js:3:1)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Module._compile (D:\WebSite_Learn\ReactJs\00--Studied--\Server Side Rendering with React and Redux\Project\MicroServices\Management\node_moSide Rendering with React and Redux\dules\pirates\lib\index.js:99:24)                                        :3:1)
    at Module._extensions..js (internal/modules/cjs/loader.js:700:10)    
    at Object.newLoader [as .js] (D:\WebSite_Learn\ReactJs\00--Studied--\e Rendering with React and Redux\ProServer Side Rendering with React and Redux\Project\MicroServices\Management\node_modules\pirates\lib\index.js:104:7) 

我不知道这个问题发生在我身上。

1 个答案:

答案 0 :(得分:0)

最终我发现了问题,我使用@ babel / register渲染应用程序的服务器端,但我忘了告诉它覆盖svg文件并且不渲染它们,所以我用这种方法处理了这个问题:

之前

// /server/index.js

require('@babel/register')
require.extensions['.scss'] = () => {};
require.extensions['.css'] = () => {};

之后

// /server/index.js

require('@babel/register')
require.extensions['.scss'] = () => {};
require.extensions['.css'] = () => {};
require.extensions['.svg'] = () => {};