There's more...

If you want to implement Babel with Webpack 4 to transpile ES6 code, you need to use babel-loader, and you may need to install the following packages:

npm install --save-dev babel-loader babel-core babel-preset-env
  1. Create a .babelrc file at the root of your project and then add this code:
    {
"presets": ["env"]
}
File: .babelrc
  1. Add our babel-loader using a webpack.config.js file:
  const webpackConfig = {
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
};

module.exports = webpackConfig;
File: webpack.config.js
  1. Create a file called src/numbers.js and import it to our src/index.js to test our babel-loader:
    export const numbers = ['one', 'two', 'three'];
File: src/numbers.js

  1. In our index.js file, do the following:
  import { numbers } from './numbers';
numbers.forEach(number => console.log(number));
File: src/index.js
  1. Run the npm run build script, and if everything works fine, you should get this result:
  1. It is also possible to use babel-loader directly in the terminal without a config file, for this, we need to use the --module-bind flag to bind an extension to a loader:
  {
"name": "webpack-zero-configuration",
"version": "1.0.0",
"description": "Webpack 4 Zero Configuration",
"main": "index.js",
"scripts": {
"build-development": "webpack --mode development --module-bind
js=babel-loader
",
"build": "webpack --mode production --module-bind js=babel-
loader
"
},
"author": "Carlos Santana",
"license": "MIT",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"webpack": "^4.6.0",
"webpack-cli": "^2.0.15"
}
}
  1. There are more flags to bind modules (if you want to learn more about Webpack CLI, you can visit the official site at https://webpack.js.org/api/cli/):
    • --module-bind-post: Bind an extension to a post-loader
    • --module-bind-pre: Bind an extension to a pre-loader
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset