不能在React组件中导入ES6模块
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
变量时,我得到的只是一个未定义的错误。
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
相关文章:
- 可以合并或嵌套ES6导入
- ES6 (ECMAScript 2015) 模块:导入索引.js
- 如何通过在Meteor中导入不同文件中的es6类来正确使用它们
- 如何将es6导入转换为AMD需要
- 如何执行“变量”ES6导入
- 使用 Babel 转译器导入类并调用带有 ES6 模块的静态方法
- 以其他名称导入 ES6 类
- React ES6 导入无状态组件
- 如何导入“;旧的“;ES6中的ES5代码
- ES6模块导入和依赖关系管理
- 如何将javascript ES6 repo编译输出导入其他repo
- 如何使用npm在ES6中导入moment.js
- 使用module.exports和ES6导出导入
- 如何有条件地导入 ES6 模块
- 解构导入ES6的价差
- 正在深层目录中导入ES6模块
- 将现有AMD模块导入ES6模块
- Ember CLI导入ES6文件到Ember - CLI -builds.js
- 不能在React组件中导入ES6模块
- 在Express提供服务的Angular2中导入ES6模块