[英]Cannot import ES6 module inside React component
我有一個名為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
變量時,得到的只是一個未定義的錯誤。
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'
};
我在這里做錯了什么?
嘗試
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.