如何使用Babel将所有包含的文件编译为一个文件? [英] How to compile all included files into one using Babel?
问题描述
我在项目中使用Babel.关键是,我的server.js
中有这行代码:
I am using Babel in my project. The thing is, I have this line of code in my server.js
:
import schema from "./data/schema";
(data/schema.js
使用ES2015语法).
(data/schema.js
is in ES2015 syntax).
当我尝试使用babel编译server.js
时,如下所示:
And when I am trying to compile my server.js
with babel, like this:
babel -o server_production.js --minified server.js
它将生成一个没有错误的新文件,并将import
指令替换为require
.但是问题是,当我尝试使用node
运行由babel编译的server.js
时,它会抱怨data/schema.js
,因为它没有被翻译成ES5,只是必需的(确切的错误是Unexpected token "import"
,因为我在data/schema.js
中使用了其他一些导入).
it produces a new file without errors and replaces import
instruction with require
. But the thing is, when I am trying to run my babel-compiled server.js
with node
, it complains about data/schema.js
, because it wasn't transpiled into ES5, only required (the exact error is Unexpected token "import"
, because I am using some other imports in data/schema.js
).
因此,问题是:如何将我的文件和所有import
的文件编译成一个文件?我尝试了babel -o server_production.js --minified data/schema.js server.js
,但是那也不起作用.
So, the question is: how can I compile my file and all the files it import
s into one file? I tried babel -o server_production.js --minified data/schema.js server.js
, but that didn't work either.
推荐答案
Babel默认情况下不捆绑依赖项.您需要使用模块捆绑器,例如汇总.
Babel doesn't bundle dependencies by default. You'll need to use a module bundler like rollup.
为此,您需要定义一个与此类似的rollup
配置:
To do this, you'll need to define a rollup
config similar to this one:
rollup.config.js
import babel from 'rollup-plugin-babel';
import babelrc from 'babelrc-rollup';
export default {
entry: 'server.js',
dest: 'server_production.js',
plugins: [
babel(babelrc())
]
};
这与下面定义的package.json
文件一起使用:
This works with the package.json
file defined below:
{
"scripts": {
"rollup": "./node_modules/.bin/rollup -c"
},
"devDependencies": {
"babel-cli": "6.14.0",
"babel-plugin-external-helpers": "6.8.0",
"babel-preset-es2015": "6.14.0",
"babelrc-rollup": "3.0.0",
"rollup": "0.35.10",
"rollup-plugin-babel": "2.6.1"
}
}
您执行命令npm run rollup -c
捆绑并编译文件.
You execute the command npm run rollup -c
to bundle and compile the files.
您将在此处找到示例: https://ide.c9.io/ifeanyidev/babel-rollup-example
You'll find an example here: https://ide.c9.io/ifeanyidev/babel-rollup-example
这篇关于如何使用Babel将所有包含的文件编译为一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!