【问题标题】:Webpack won't resolve modules without .jsx extension despite resolve being set尽管设置了解析,但 Webpack 不会解析没有 .jsx 扩展名的模块
【发布时间】:2016-08-27 12:05:02
【问题描述】:

如果我将 .jsx 添加到 require('./StringOption') 它可以工作,但我认为我的 webpack.config.js 的 resolve 部分应该允许我不需要扩展名。我做错了什么?

./ infront 与 index.jsx 位于同一目录时,为什么我还需要它?

运行 webpack 后的错误信息:

ERROR in ./src/index.jsx
Module not found: Error: Cannot resolve module 'StringOption' in /Users/Mike/packages/chrome-extension-options/src
 @ ./src/index.jsx 5:19-42

index.js:

'use strict'

var React = require('react')
var ReactDOM = require('react-dom')
var StringOption = require('./StringOption');

ReactDOM.render(<StringOption id="test" name="Test" />, document.getElementById('content'))

webpack.config.js 文件:

var path = require("path");

module.exports = {
    entry: './src/index.jsx',
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: 'index.js'
    },
    module: {
        loaders: [
            {
                test: /\.jsx$/,
                loader: 'jsx-loader',
                exclude: /node_modules/
            }
        ]
    },
    externals: {
        'react': 'React',
        'react-dom': 'ReactDOM'
    },
    resolve: {
        extensions: ['', '*.js', '*.jsx']
    }
};

目录结构:

- src/
  - index.jsx
  - StringOption.jsx
- dist/
  - index.js
  - react.js
  - react-dom.js

【问题讨论】:

  • 你试过resolve: { extensions: ['', '.js', '.jsx'], }看到这个问题:stackoverflow.com/questions/34678314/…
  • @alexi2 你是个天才。谢谢你。我看到了那个帖子,但没有注意到他们没有放星号。现在我已经删除了它们。

标签: javascript reactjs webpack


【解决方案1】:

首先 ./StringOption 说它应该在同一目录中搜索。与其他地方不同,我们需要在 react jsx 中指定我们需要从哪里导入文件。

其次

在resolve中你不需要显式使用resolve,只需使用babel-loader或者使用resolve作为

resolve: {
    extensions: ['', '.js', '.jsx']
}

module: {
        loaders: [
            {
                test: /\.jsx$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            }
        ]
    }

【讨论】:

    【解决方案2】:

    在您的 webpack.config.js 中包含以下内容,这样您就不必担心 js 和 jsx 扩展。

        loaders: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                // include: __dirname + '/src',
                include: path.join(__dirname, '/src'),
                loader: 'babel-loader',
                query: {
                    presets: ['react','es2015']
                }
           }]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-17
      • 2019-11-15
      • 2019-02-03
      • 2019-07-07
      • 2021-11-24
      • 2017-04-17
      • 2017-08-07
      • 1970-01-01
      相关资源
      最近更新 更多