[英]How to import javascript export file generated from the webpack.config?
[英]How to import constant from config file to another file with JavaScript Webpack
我剛剛開始使用JS,Webpack,React。 我創建了一個簡單的React應用程序,它調用API並在該調用的結果中顯示頁面上的一些數據。 這一切都很好用api鍵硬編碼但我想保持api鍵作為配置文件中的常量,被git忽略。
我創建了一個包含以下內容的config.js文件:
export const API_KEY = 'myApiKey';
現在,我想將此常量導入另一個負責進行API調用的文件index.js 。 我使用以下代碼進行導入:
import * as config from '../config.js';
通過這樣做,我雖然可以通過以下方式訪問api密鑰 :
config.API_KEY
但是,在構建應用程序時,我收到以下錯誤:
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]
我的項目文件結構如下:
project
-src
--api
---index.js
-config.js
-webpack.config.js
我試圖將config.js放在與index.js相同的文件夾中,但這也不起作用。 我已經搜索了很多,試圖弄清楚這一點,也許這是一個非常基本的問題,但我還沒有找到解決方案。 我真的很感激任何指導。 謝謝! 安娜
在文件src/api/index.js
您嘗試導入../config.js
和../
表示它應該在當前文件的父目錄中,因此它會查找文件src/config.js
,但是那不存在。 你需要再上一個目錄。
您的導入應該是:
import * as config from '../../config.js';
如果要從當前目錄導入文件,可以使用./
,如下所示:
import * as config from './config.js';
您還可以為文件或目錄定義別名 - 因此您無需定義完整路徑和擴展名。 在你的webpack.config.js
:
resolve: {
modules: [
path.resolve(__dirname, ""),
"node_modules"
],
extensions: [ "", ".js", ".jsx" ]
},
所以為了從任何地方訪問你的config.js -
import * as config from "config"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.