乐闻世界logo
搜索文章和话题

How to use Babel without Webpack

1个答案

1

Using Babel without Webpack, you can directly use the Babel CLI or integrate it with other task runners like Gulp or Grunt. Below are the basic steps to use the Babel CLI:

1. Install Node.js and npm

Ensure Node.js and npm are installed in your development environment. Download and install them from the official Node.js website.

2. Initialize the npm Project

In the project root directory, run the following command to initialize a new npm project (if you don't already have a package.json file):

bash
npm init -y

3. Install Babel

Install the Babel CLI and Babel preset (e.g., @babel/preset-env):

bash
npm install --save-dev @babel/core @babel/cli @babel/preset-env

4. Configure Babel

Create a .babelrc or babel.config.json file in the project root directory to configure Babel. For example:

json
{ "presets": ["@babel/preset-env"] }

5. Create a Babel Transformation Script

In the package.json file, add an npm script to run Babel and transform your JavaScript files. For example:

json
{ "scripts": { "build": "babel src -d dist" } }

The "build" script transforms all JavaScript files in the src directory into ES5 and outputs them to the dist directory.

6. Run Babel

Execute the script you created to transform your code with the following command:

bash
npm run build

7. (Optional) Use Other Tools

For additional build steps (such as code minification or file copying), consider using task runners like Gulp or Grunt, which can be combined with Babel.

8. Use the Transformed Code in the Browser

Ensure your HTML file references the transformed JavaScript file. For example, if your original file is src/app.js, the transformed file might be dist/app.js.

html
<script src="dist/app.js"></script>

Notes:

  • Verify that your .babelrc or babel.config.json file is configured with the appropriate Babel plugins and presets for your project.
  • When using the CLI, you may need to install additional Babel plugins or presets to support specific language features.
  • If transforming Node.js code, ensure your Node.js version is compatible with the Babel plugins you are using.

These steps will help you transform your JavaScript code using Babel without Webpack.

2024年6月29日 12:07 回复

你的答案