在 NextJS 中,引用包含 SVG 的外部 npm 包时如何构建?

wil*_*lem 6 svg webpack babeljs next.js

我的 nextjs 项目(我们称之为 TheHost)引用了另一个 npm 包(我们称之为 ThePackage)。

在 TheHost 中定义时,SVG 加载良好,但导入 ThePackage 失败,因为 next 尝试将 svg 解释为 javascript...所以我在执行以下操作时收到以下错误next build

SyntaxError: Unexpected token '<'
Run Code Online (Sandbox Code Playgroud)

重申一下,当引用 TheHost 本身定义的 svg 时,SVG 可以正常工作。问题似乎是导入包含 SVG 的 npm 包。

我是否从 ThePackage 导入一个使用 SVG 的组件并不重要,只是在 npm 包中的某处包含一个“import xxx from '../path/to/svg' 就足以破坏next build.

对于它的价值,ThePackage 的转译 javascript 读取 svg 如下:

var _mysvg = require("../path/to/the-svg.svg");
Run Code Online (Sandbox Code Playgroud)

很多细节:

下一个构建堆栈跟踪是:

> Using external babel configuration
> Location: "/Users/w/dev/TheHost/.babelrc"
Creating an optimized production build

Compiled successfully.

> Build error occurred
/Users/w/dev/TheHost/node_modules/ThePackage/build/assets/card_background.svg:1
<svg viewBox="0 0 860 382" fill="none" xmlns="http://www.w3.org/2000/svg">
^

SyntaxError: Unexpected token '<'
    at Module._compile (internal/modules/cjs/loader.js:895:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Module.require (internal/modules/cjs/loader.js:852:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/Users/w/dev/TheHost/node_modules/TheProject/build/card/style.js:14:47)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32) {
  type: 'SyntaxError'
}
Automatically optimizing pages .%
Run Code Online (Sandbox Code Playgroud)

.babelrc 文件:

{
  "presets": [
    "next/babel"
  ],
  "plugins": [
    "babel-plugin-styled-components",
    "inline-react-svg"
  ]
}
Run Code Online (Sandbox Code Playgroud)

next.config.js 文件:

const withSourceMaps = require("@zeit/next-source-maps");
const withImages = require("next-images");

module.exports = withImages(
  withSourceMaps({
    env: { *** redacted *** },
    publicRuntimeConfig: { *** redacted *** },
    webpack: (config, options) => {
      if (!options.isServer) {
        config.resolve.alias["@sentry/node"] = "@sentry/browser";
      }
      config.module.rules.push({
        test: /\.svg$/,
        use: ["@svgr/webpack"]
      });
      return config;
    }
  })
);
Run Code Online (Sandbox Code Playgroud)

nextjs svgr 包版本如下:

"next": "^9.2.1",
"next-images": "^1.3.0",
"@svgr/webpack": "^5.1.0",
"babel-eslint": "^10.0.3",
"babel-plugin-inline-react-svg": "^1.1.1",
Run Code Online (Sandbox Code Playgroud)

ThePackage 使用以下输出配置(webpack)构建:

  entry: './src/index.js',
  output: {
    path: buildFolder,
    filename: 'ThePackage.js',
    library: 'ThePackage',
    libraryTarget: 'umd', /* Note: umd */
    umdNamedDefine: true
  },
Run Code Online (Sandbox Code Playgroud)

小智 11

NextJSnode_modules默认忽略,所以你需要特别允许你的配置能够转译你的包。幸运的是,有人已经创建了一个 NextJS 插件来允许这样做:https : //github.com/martpie/next-transpile-modules

我还建议使用Next Compose Plugins来整理配置。最后,您的 next.config.js 将如下所示:

const withSourceMaps = require("@zeit/next-source-maps");
const withImages = require("next-images");
const withPlugins = require('next-compose-plugins');
const withTM = require('next-transpile-modules')(['ThePackage']);

module.exports = withPlugins([
    withTM,
    [
        withImages,
        {
            exclude: /\.svg$/
        }
    ],
    withSourceMaps
],
{
    env: { *** redacted *** },
    publicRuntimeConfig: { *** redacted *** },
    webpack: (config, options) => {
      if (!options.isServer) {
        config.resolve.alias["@sentry/node"] = "@sentry/browser";
      }
      config.module.rules.push({
        test: /\.svg$/,
        use: ["@svgr/webpack"]
      });
      return config;
    }
});
Run Code Online (Sandbox Code Playgroud)

我还排除了 SVG 的处理withImages