我有不同的 JS 文件,我必须使用 Babel 来创建单个 JS 包。
他们向我推荐了第一个链接,但我不知道如何:https://babeljs.io/docs/usage/cli/
在互联网上浏览我发现了第二个链接:http://ccoenraets.github.io/es6-tutorial-data/babel-webpack/这使我有义务首先使用第三个:http://ccoenraets.github.io/es6-tutorial/setup-babel/
第二个和第三个链接是否是学习如何创建单个 JS 包的可行形式?还有其他好的和简单的选择吗?
最佳答案
我不确定你是否可以使用 babel 作为打包工具。但是,由于您是新手,我建议您查看 webpack。如果这是一个选项,请继续阅读
您的文件夹结构最初可能类似于以下内容
project folder
|
|-src
| |
| |- index.js
| |- moduleOne.js
| |- moduleTwo.js
|
|- index.html
|- webpack.config.js
index.html
<!doctype html>
<html>
<head>
<title>Sample</title>
</head>
<body>
content
<script src="dist/bundle.js"></script>
</body>
</html>
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
};
moduleOne.js
export default class moduleOne {
constructor() {
console.log('moduleOne constructor');
}
someFunc(text){
console.log(text);
}
}
moduleTwo.js
export default class moduleTwo {
constructor() {
console.log('moduleTwo constructor');
}
someFunc(text){
console.log(text);
}
}
在命令行窗口中,导航到项目文件夹并键入 npm install webpack --save-dev
然后运行 webpack
来打包文件。这将创建一个 dist
文件夹,其中包含 bundle.js
文件。
现在,如果您在浏览器上打开 index.html
,您应该会看到以下控制台输出。
moduleOne constructor
moduleTwo constructor
moduleOne.someFunc
moduleTwo.someFunc
简而言之,index.js
导入了 moduleOne.js
和 moduleTwo.js
,实例化了它们并调用了 someFunc( )
方法。 Webpack 将所有这些 bundle 到 dist/bundle.js
中。这是一个快速设置,但希望您能理解
来源:webpack
关于javascript - 使用 Babel 创建单个 JavaScript 包的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50441651/