Webpack JSX无法通过ES6导入解析相关模块

时间:2018-09-28 00:59:45

标签: javascript reactjs webpack babeljs

我正在为一个已经存在的大型React App设置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"]
}

话虽这么说,关于为什么某些相对进口失败的任何想法,我该如何解决?

1 个答案:

答案 0 :(得分:1)

您需要添加解析扩展。在Webpack中添加以下配置,然后重新启动React app

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