使用babel编译.jsx文件而不是.js [英] Compile .jsx files instead of .js using babel
问题描述
我开始学习ReactJs
,我正尝试使用.
I'm starting to learn ReactJs
, and I was trying to build an environment from scratch using this "builder".
一切正常,但我想使用.jsx
文件而不是.js
(否则,文本编辑器会搞砸,否则使用未编译脚本的其他扩展名会更好)
Everything works pretty well, but I'd like to work with .jsx
files instead of .js
(the text editor screws up otherwise, and ir feels better using a different extension for not-compiled scripts)
但是,我没有设法编译这样的.jsx
文件,它仅适用于.js
文件.
However, I didn't manage to compile such .jsx
files, it only works with .js
files.
这是.babelrc
的配置文件:
{
"presets":["es2015","react"]
}
还有我的webpack.config.js
:
var path = require('path');
var config = {
context: path.join(__dirname,'src'),
entry:[
'./main.js'
],
output:{
path :path.join(__dirname,'www'),
filename:'bundle.js'
},
module:{
loaders:[
{
test: /\.js$/,
exclude:/node_modules/,
loaders:['babel']
}
],
},
resolveLoader:{
root: [
path.join(__dirname,'node_modules')
]
},
resolve:{
root:[
path.join(__dirname,'node_modules')
]
}
};
module.exports = config;
我试图简单地将webpack配置文件中的扩展名从js
更改为jsx
,但无济于事.
有什么想法吗?
I tried simply changing the extensions in the webpack config file from js
to jsx
, but to no avail.
Any ideas?
推荐答案
只需替换此行:
test: /\.js$/,
具有:
test: /\.jsx$/,
它将在.jsx
文件而不是 .js
文件上运行babel loader.
It will run babel loader on the .jsx
files, instead of .js
files.
如果要同时翻译 和.jsx
,可以将其设置为/\.jsx?$/
,其中正则表达式中的?
表示匹配前面的字符的0或1次出现:.js
和.jsx
均为阳性.
If you want to transpile both .js
and .jsx
, you can set it to /\.jsx?$/
, where ?
in regex indicates to match 0 or 1 occurrences of the preceding character: test positive for both .js
and .jsx
.
.test
属性指示运行loader
键中指定的加载程序必须满足的条件.您可以在此处阅读更多有关module.loader
选项的信息.
.test
property indicates a condition that must be met to run the loader specified in the loader
key. You can read more about module.loader
options here.
此外,在导入模块时,应添加.jsx
扩展名,如下所示:
Also, when importing modules, you should add the .jsx
extension, like this:
import Counter from './Counter.jsx';
或设置webpack的 resolve.extensions
配置以添加.jsx
扩展名(默认情况下,它仅查找.js文件).像这样:
Or set webpack's resolve.extensions
config to add .jsx
extension (by default, it looks only for .js files). Like this:
resolve: {
/* ... */
extensions: ['', '.js', '.jsx']
}
这样,您可以导入不带扩展名的文件:
This way, you can import your files without the extension:
import Counter from './Counter';
这篇关于使用babel编译.jsx文件而不是.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!