【问题标题】:Webpack JSX cannot resolve relative module through ES6 importsWebpack JSX 无法通过 ES6 导入解析相关模块
【发布时间】:2019-03-03 22:54:29
【问题描述】:

我正在为一个已经存在的大型 React 应用程序设置 webpack。 似乎工作正常,但某些模块会导致麻烦,除非我专门将扩展添加到导入中

//not working
import AppRouter from './router';

//working but meh
import AppRouter from './router.jsx';

它不会出现在所有相对导入中,但我看到的一些看起来是随机的。


错误,不同文件多次出现

 ERROR in ./src/main/resources/js/cs/index.js
    Module not found: Error: Can't resolve './router' in '<ommited_path>/src/main/resources/js/cs'
     @ ./src/main/resources/js/cs/index.js 

该文件的文件夹结构

/src
--/main
  --/resources
     --/js/
        --/cs
           index.js
           router.jsx
           store.js

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const paths = require('./config/paths');

const config = {
    entry: {
        index: path.join(__dirname, paths.custServReactIndex),
    },
    output: {
        path: path.join(__dirname, paths.outputScriptsFolder),
        filename: '[name].js',
        publicPath: paths.outputScriptsFolder,
    },
    mode: 'development',
    module: {
        rules: [
            {
                // Compile main index
                test: /\.jsx?$/,
                loader: 'babel-loader',
            },
        ],
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
        }),
    ],
};

module.exports = config;

.babelrc

{
    "ignore": ["node_modules"],
    "presets": ["env", "stage-0", "react"]
}

话虽如此,关于为什么某些相关导入失败以及如何解决这个问题的任何想法?

【问题讨论】:

    标签: javascript reactjs webpack babeljs


    【解决方案1】:

    您需要添加解析扩展。在 Webpack 中添加以下配置并重启 React 应用

      resolve: {
          modules: [
            path.resolve("./src"),
            path.resolve("./node_modules")
          ],
          extensions: [".js", ".jsx"]
      }
    

    【讨论】:

      猜你喜欢
      • 2016-11-26
      • 2023-03-15
      • 2019-11-15
      • 2018-11-12
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 2021-07-21
      • 2022-01-25
      相关资源
      最近更新 更多