Javascript scope when importing modules

℡╲_俬逩灬. 提交于 2020-01-07 00:36:53

问题


Could anyone explain why I can't print external: bar in the following example? As far as I know, the imported function externalFunction should be added to the global scope, and when invoked, should have the same scope than localFunction, isn't it?

entry.js

import { f as externalFunction } from './myfunction.js'

function localFunction() {
  console.log('local: ' + foo) // 'local: foo'
  console.log('local: ' + bar) // 'local: bar'
}

foo = 'foo'
var bar = 'bar'

localFunction()
externalFunction()

myfunction.js

export const f = function() {
  console.log('external: ' + foo) // 'foo'
  console.log('external: ' + bar) // 'ReferenceError: bar is not defined'
}

webpack.config.js

const webpack = require('webpack')
const path = require('path')

module.exports = [
  {
    // define the entry points
    entry: {
      viewer: './entry.js'
    },
    // create a sourcemap file alongside the bundle file for easy debugging
    devtool: 'source-map',
    // Define the path and filename for the bundled modules
    output: {
      path: './',
      filename: 'bundle.js'
    },
    module: {
      // Define all the loaders we want to use
      loaders: [
        {
          test: /.js$/,
          loader: 'babel-loader',
          exclude: /node_modules/,
          query: {
            presets: ['es2015-without-strict']
          }
        }
      ]
    }
  }
];

And then just running this in the browser where the bundle is just added through a tag.

来源:https://stackoverflow.com/questions/38270470/javascript-scope-when-importing-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!