|
Post by account_disabled on Jan 25, 2024 2:30:02 GMT -6
在本文中,我们将研究使用Babel和webpack创建一个构建设置来处理现代 JavaScript(在 Web 浏览器中运行) 。 Pause Next Unmute Current Time 0:09 / Duration 2:00 Fullscreen 这是为了确保我们的现代 JavaScript 代码能够与更广泛的浏览器兼容。 JavaScript 与大多数 Web 相关技术一样,一直在发展。在过去的美好时光,我们可以将几个<script>标签放入一个页面中,也许包括 jQuery 和几个插件,然后就可以开始了。 然而,自从 ES6 推出以来,事情变得越来越复杂。浏览器对新语言功能的支持通常是不完整的,随着 JavaScript 应用程序变得更加雄心勃勃,开发人员开始使用模块来组织他们的代码。反过来,这意味着如果您现在正在编写现代 JavaScript,则需要在流程中引入构建步骤。 正如您从下面的链接中看到的,从 ES6 转换到 ES5 极大地增加了我们可以支持的浏览器数量。 ES6 兼容性 ES5 兼容性 Learn to Code with JavaScript 构建系统的目的是自动化使我们的代码为浏览器和生产做好准备所需的工作流程。这可能包括将代码转译为不同标准、将 Sass 编译为 CSS、捆绑文件、缩小和压缩代码等步骤。为了确保这些步骤始终 WhatsApp 号码数据 可重复,需要一个构建系统从单个命令以已知顺序启动这些步骤。 先决条件 为了继续进行,您需要安装Node.js 和 npm(它们打包在一起)。我建议使用版本管理器(例如nvm )来管理 Node 安装(具体方法如下),如果您需要一些帮助来掌握 npm,请查看 SitePoint 的适合初学者的 npm 教程。 设置 在计算机上的某个位置创建一个根文件夹,然后从终端/命令行导航到该文件夹。这将是您的<ROOT>文件夹。 使用以下命令创建一个package.json文件: npm init -y 注意:该-y标志使用默认设置创建文件,这意味着您不需要从命令行完成任何常见的详细信息。 如果您愿意,可以稍后在代码编辑器中更改它们。 在您的 ROOT文件夹中,创建目录。该src/js文件夹将是我们放置未处理的源代码的位置,该public文件夹将是转译代码最终所在的位置。 使用 Babel 进行转译t 为了让我们继续前进,我们将安装babel-cli,它提供了将 ES6 转换为 ES5 的能力,以及babel-preset-env,它允许我们使用转换后的代码来定位特定的浏览器版本。 您现在应该在您的 中看到以下内容当我们在package.json文件中时,让我们将该scripts部分更改为如下所示这使我们能够通过脚本调用 Babel,而不是每次都直接从终端调用。如果您想了解有关 npm 脚本及其功能的更多信息,请查看此 SitePoint 教程。 最后,在我们测试 Babel 是否正常工作之前,我们需要创建一个.babelrc配置文件。这就是我们的babel-preset-env包将引用的转译参数。
|
|