MENU

解决raw-loader引入文件后内容为export default......

背景

在给项目添加新模块时用到了react-markdown这个组件,由于没有数据源,便使用了项目目录下src/markdown/summary.md文件进行引入作为源,在引入过程中用到了raw-loader组件并修改了webpack.config.js,修改部分如下:

rules: [
   {
     test: /\.md$/,
     use: "raw-loader"
   },
...

问题描述

在安装好依赖,修改好配置文件并在App.js中引入.md文件后运行项目,发现引入的内容并不正确:本应该显示文件内容的地方只显示了一行字符串export default __webpack_public_path__ + "$summary.1a7bea09.txt"

问题分析

  • 检查raw-loader配置是否出错或丢失后排除:项目是正常启动并运行的,且输出的字符串的确与未配置webpack引入的内容不同
  • 检查是否由于webpack5中的asset module导致的:该项目使用webpack版本是4.44.2,故排除
  • 检查raw-loader版本的问题:回退到0.5.1版本后,问题并未得到解决

检查配置

突然发现造成这种问题的原因应该是在资源被导入时使用了file-loader而非raw-loader,再次检查webpack.config.js后发现如下内容:

{
    loader: require.resolve('file-loader'),
    // Exclude `js` files to keep "css" loader working as it injects
    // its runtime that would otherwise be processed through "file" loader.
    // Also exclude `html` and `json` extensions so they get processed
    // by webpacks internal loaders.
    exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
    options: {
        name: 'static/media/[name].[hash:8].[ext]',
    },
},

file-loader配置的下方发现了如下两行注释

// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.

解决方案

raw-loader配置添加到file-loader之前即可解决

{
    test: /\.md$/,
    use: "raw-loader"
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
    loader: require.resolve('file-loader'),
    // Exclude `js` files to keep "css" loader working as it injects
    // its runtime that would otherwise be processed through "file" loader.
    // Also exclude `html` and `json` extensions so they get processed
    // by webpacks internal loaders.
    exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
    options: {
        name: 'static/media/[name].[hash:8].[ext]',
    },
},

// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.

文章标题:解决raw-loader引入文件后内容为export default......
如果文中内容侵犯了您的权益,请及时与博主取得联系进行删除!
本站文章未经许可禁止转载,本文地址:https://blog.wanvale.com/archives/433/

Archives QR Code Tip
QR Code for this page
Tipping QR Code