导入 mp3 时出现“找不到模块”错误

时间:2021-04-08 11:33:58

标签: typescript webpack next.js

我在 NextJS 应用程序中使用 useSound,我想播放位于 /public/static 中的 mp3:

import notification from "../../public/static/notification.mp3"

它在运行 yarn dev 时有效(正在播放声音,没有错误),但在使用 yarn prod 构建时会引发错误:

Type error: Cannot find module '../../public/static/notification.mp3' or its corresponding type declarations.

有人可以帮我吗?我一直在浏览互联网/SO/github,并尝试了几件事,包括修改next.config.js

  webpack(config, { isServer }) {
    config.module.rules.push({
      test: /\.(ogg|mp3|wav|mpe?g)$/i,
      exclude: config.exclude,
      use: [
        {
          loader: require.resolve('url-loader'),
          options: {
            limit: config.inlineImageLimit,
            fallback: require.resolve('file-loader'),
            publicPath: `${config.assetPrefix}/_next/static/`,
            outputPath: `${isServer ? '../' : ''}static/`,
            name: '[name]-[hash].[ext]',
            esModule: config.esModule || false,
          },
        },
      ],
    });
    return config;
  },

没有成功..

1 个答案:

答案 0 :(得分:0)

好吧,显然就是这么简单:用

更新next-env.d.ts
declare module '*.mp3' {
  const src: string;
  export default src;
}

如果有人能解释它是如何工作的,那就太好了。