Clafouti
Clafouti

Reputation: 4595

Cannot import ES6 module inside React component

I have a config file named config.js that looks like this :

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

module.exports = config;

I also use Webpack to give alias to my modules so I have this line in my webpack.config.js :

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

I then try to import my config file with this :

import config from 'configFile';

Inside a React Component. However, when I try to access configvariable, all I get is an undefined error.

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'
};

What am I doing wrong here ?

Upvotes: 0

Views: 677

Answers (3)

slopeofhope
slopeofhope

Reputation: 776

Try

 import * as config from 'configFile';

And try console.log the config variable and see if you get not defined. If it is still not defined, the problem lies in exporting the configFile.

Upvotes: 1

madox2
madox2

Reputation: 51841

You should define relative path to root:

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

or relative to contentBase

Upvotes: 0

Everettss
Everettss

Reputation: 16029

Your path 'app/config.js' will the most probably point to node_modules/app/config.js.

The simplest solution will be changing your path in alias to absolute (or more proper in your scenario):

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

Upvotes: 0

Related Questions