不能在React组件中导入ES6模块

Cannot import ES6 module inside React component

本文关键字:导入 ES6 模块 组件 React 不能      更新时间:2023-09-26

我有一个名为config.js的配置文件,看起来像这样:

var config = {};
config.web = {};
config.web.param = 'oneParam';
module.exports = config;

我还使用Webpack给我的模块别名,所以我在我的Webpack .config.js中有这一行:

alias: {
  configFile: 'app/config.js'
}

然后尝试导入我的配置文件:

import config from 'configFile';

在React组件内部。然而,当我试图访问config变量时,我得到的只是一个未定义的错误。

My full webpack.config.js

var webpack = require('webpack');
module.exports = {
  entry: [
    './app/app.jsx'
  ],
  output: {
      path: __dirname,
      filename: './dist/bundle.js'
  },
  externals: {
    'Config': JSON.stringify()
  },
  resolve: {
    root: __dirname,
    alias: {
      configFile: 'app/config.js'
    },
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-0']
        },
        test: /'.jsx?$/,
        exclude: /(node_modules|bower_components)/
      },
      {test: /'.scss?$/, exclude: /node_modules/, loader: "style-loader!css-loader!sass-loader!"},
      {test: /'.css?$/, loader: "style-loader!css-loader!"},
      {test: /'.(png|jpg)$/, loader: "file-loader?name=./dist/images/[name].[ext]"}
    ]
  },
  devtool: 'cheap-module-source-map'
};

我哪里做错了?

Try

 import * as config from 'configFile';

并尝试console.log配置变量,看看是否没有定义。如果仍然没有定义,问题在于导出configFile。

您的路径'app/config.js'将最有可能指向node_modules/app/config.js

最简单的解决方案是将别名中的路径更改为绝对路径(或者在您的场景中更合适):

alias: {
  configFile: '/app/config.js'
}

你应该定义到根目录的相对路径:

alias: {
  configFile: './app/config.js'
}

或相对于contentBase