How to use ES6 import/export with Webpack 4?

The modern solution is to use node.js 13+, then add "type": "module" to your package.json file. This will allow you to use import syntax instead of require. More info here https://nodejs.org/dist/latest-v13.x/docs/api/esm.html

Webpack still needs the require syntax, so you will have to rename webpack.config.js to webpack.config.cjs and then let webpack know what's the new config file by adding webpack --config webpack.config.cjs to your package.json script command. Keep an eye here https://github.com/webpack/webpack-cli/issues/1165 if webpack fixes their issue with require

This means you don't need any babel or any transpiler.


You need to transpile it using babel & use babel-loader.

Also, you don't need to use make just use npm scripts.

There are mistakes like importing import { hello } from 'hello.js' instead it should be import { hello } from './hello.js' or without .js like import { hello } from './hello'

Try the following -

npm install --save-dev babel-core babel-loader babel-preset-env webpack@next webpack-cli

src/app.js

import { hello } from "./hello";
hello();

src/hello.js

function hello() {
  console.log("yes it's hello");
}
export { hello };

webpack.config.js

const path = require("path");

module.exports = {
  entry: "./src/app.js",

  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js"
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        loader: "babel-loader",
        exclude: /(node_modules)/
      }
    ]
  }
};

package.json

{
  "name": "webpack-test",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "build": "webpack --mode development",
    "prod": "webpack --mode production",
    "start": "node dist/bundle.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.6.1",
    "webpack": "^4.0.0-beta.3",
    "webpack-cli": "^2.0.11"
  }
}

.babelrc

{
  "presets": ["env"]
}

First run npm run build or npm run prod & then run npm run start which will log the output