简体   繁体   中英

Setting WebPack & Babel to use ES6 modules but gets Uncaught ReferenceError: function is not defined

I'm just getting started with Webpack & Babel to take advantage of exporting ES6's modules.

My build setup generates build/main.build.js used in index.html but browser console shows error: Uncaught ReferenceError: calculateInterest is not defined

As, I'm new to this, I'm not sure where the problem actually lies, is it in the my webpack.config.js or package.json setup or the exporting and importing modules or in the compiled build/main.build.js .

Can anybuddy help me get this setup right. Here are the build files.

package.json

{
  "name": "learn-webpack",
  "version": "1.0.0",
  "description": "A shot at learning WebPack",
  "main": "index.html",
  "scripts": {
    "start": "http-server",
    "webpack": "webpack"
  },
  "keywords": [
    "webpack",
    "learn-webpack"
  ],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "webpack": "^4.16.1"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-preset-es2015": "^6.24.1",
    "http-server": "^0.11.1",
    "webpack": "^4.16.1",
    "webpack-cli": "^3.1.0"
  }
}

Webpack.config.js

const path = require('path') 

module.exports = {
    entry: './scripts/main.js',
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'main.bundle.js'
    },

    module: {
         rules: [
             {
                 test: /\.js$/,
                 use: [{
                    loader: 'babel-loader',
                    query: {
                         presets: ['es2015']
                    }
                 }]
             }
         ]
     },
     optimization: {
        minimize: false
     },

     mode: 'development',

     stats: {
         colors: true
     }
 };

Index.html

<head>
    <title>Babel Learning</title>
    <link href="css/style.css" type="text/css" rel="stylesheet">
    <script src="build/main.bundle.js" type="text/javascript"></script> 
</head>
<body onload="init()">

    <button id="btn">Calculate Interest</button>

    <div id="result"></div>

<script>
    function init() {
        var btn = document.getElementById('btn')
        var result = document.getElementById('result')


        btn.addEventListener('click', function(){
            var interest = calculateInterest(3000,29,1)
            result.innerHTML = interest
        })
    }
</script>

</body>
</html>

scripts/main.js

import getSI from './js/getSI.js'

scripts/js/getSI.js

export function calculateInterest(principal, rate, time) {
    var interest = (principal * rate * time) / 100
    return interest
}

Thanks for your help. Much appreciated.

appu

You can export the functions you want to from main.js :

  import { calculateInterest } from './js/getSI.js';
  export { calculateInterest };

and change your webpack output settings to

  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'main.bundle.js',
    libraryTarget: 'this',
    library: 'LearnWebpack'
  },

In doing so you will get LearnWebpack available in browser

  <script>
  function init() {
    var btn = document.getElementById('btn')
    var result = document.getElementById('result')
    btn.addEventListener('click', function() {
      var interest = LearnWebpack.calculateInterest(3000, 29, 1)
      result.innerHTML = interest
    })
  }
  </script>

Here you can find details about webpack 's libraryTarget available settings. From what I know these settings ( library ) are for libraries but it should get your experiments going.

I found a similar issue in this older post - same idea but the used settings are for webpack@2 (I think) Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM