解决create-react-app项目无法引用src文件夹外的资源问题

11-07
评论
字数统计:2241(字)
使用create-react-app创建的项目,无法在项目内引用src文件夹外的资源,比如:import 一个 ../src的文件。尝试了很多办法,终于找到有效的解决方案。不容易啊~

使用craco覆盖webpack配置

修改craco.config.js文件

// 先解除限制src/以外的文件资源
const definePlugin = webpackConfig.plugins.find(({ constructor }) => {
    return constructor && constructor.name === 'DefinePlugin';
});

const scopePluginIndex = webpackConfig.resolve.plugins.findIndex(({ constructor }) => {
    return constructor && constructor.name === 'ModuleScopePlugin';
});

definePlugin.definitions['process.env'] = {
    ...definePlugin.definitions['process.env']
};
webpackConfig.resolve.plugins.splice(scopePluginIndex, 1);
// 添加loader以支持引用src/外资源
const { isFound, match } = getLoader(
    webpackConfig,
    loaderByName("babel-loader")
);
if (isFound) {
    const include = Array.isArray(match.loader.include)
      ? match.loader.include
      : [match.loader.include];

    match.loader.include = include.concat(packages);
}

完整craco.config.js文件

const path = require('path');
const { getLoader, loaderByName } = require("@craco/craco");

const packages = [];
packages.push(path.join(__dirname, "./@types"));

module.exports = {
  webpack: {
    alias: {
      '@': path.resolve(__dirname, 'src/'),
      types: path.resolve(__dirname, '@types/'),
      dist: path.resolve(__dirname, 'dist/')
    },
    configure: webpackConfig => {
      const definePlugin = webpackConfig.plugins.find(({ constructor }) => {
        return constructor && constructor.name === 'DefinePlugin';
      });

      const scopePluginIndex = webpackConfig.resolve.plugins.findIndex(({ constructor }) => {
        return constructor && constructor.name === 'ModuleScopePlugin';
      });

      definePlugin.definitions['process.env'] = {
        ...definePlugin.definitions['process.env']
      };
      webpackConfig.resolve.plugins.splice(scopePluginIndex, 1);

      const { isFound, match } = getLoader(
        webpackConfig,
        loaderByName("babel-loader")
      );
      if (isFound) {
        const include = Array.isArray(match.loader.include)
          ? match.loader.include
          : [match.loader.include];

        match.loader.include = include.concat(packages);
      }
      return webpackConfig;
    }
  }
};

本文链接:https://blog.crazylei.com/art/fb22efb5
版权声明: 本博客所有文章除特别声明外,均采用CC BY 4.0 CN协议 许可协议。转载请注明出处!

评论

正在加载评论...

©2022 Crazylei Bolg沪ICP备20001821号