简体   繁体   中英

How to import constant from config file to another file with JavaScript Webpack

I am just getting started with JS, Webpack, React. I created a simple React application that makes a call to an API and displays some data on a page as a result of that call. It all works fine with the api key hardcoded but I want to keep the api key as a constant in a config file which is ignored by git.

I created a config.js file that contains this:

export const API_KEY = 'myApiKey';

Now, I want to import this constant into another file index.js responsible for making the API calls. I used the following code to make the import:

import * as config from '../config.js';

By doing that, I though I could access the api key by with:

config.API_KEY

However when building the application I get the following error:

ERROR in ./src/api/index.js
Module not found: Error: Can't resolve '../config.js' in 
'/Users/ana/code/fundraiser-leaderboard/src/api'
 @ ./src/api/index.js 13:14-37
 @ ./src/components/Fundraisers.js
 @ ./src/components/App.js
 @ ./src/index.js
Child html-webpack-plugin for "index.html":
       [0] (webpack)/buildin/amd-options.js 82 bytes {0} [built]
       [1] ./~/lodash/lodash.js 478 kB {0} [built]
       [2] (webpack)/buildin/global.js 823 bytes {0} [built]
       [3] (webpack)/buildin/module.js 521 bytes {0} [built]
       [4] ./~/html-webpack-plugin/lib/loader.js!./src/index.html 663 bytes 
   {0} [built]

My project file structure looks like:

project
-src
--api
---index.js
-config.js
-webpack.config.js

I have tried to put config.js in the same folder as index.js but that didn't work either. I have searched a lot to try and figure this out and perhaps it is a pretty basic problem but I could not find a solution yet. I would really appreciate any guidance. Thank you! Ana

In the file src/api/index.js you try to import ../config.js and ../ means it should be in the parent directory of the current file, therefore it looks for the file src/config.js , but that doesn't exist. You need to go up one more directory.

Your import should be:

import * as config from '../../config.js';

If you want to import a file from the current directory you would use ./ , like this:

import * as config from './config.js';

You can also define aliases for the files or directories - so you will not need to define the full path and extension. In your webpack.config.js :

resolve: {
  modules: [
    path.resolve(__dirname, ""),
    "node_modules"
  ],

  extensions: [ "", ".js", ".jsx" ]
},

So in order to access your the config.js from anywhere -

import * as config from "config"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM