使用webpack定义全局变量 [英] Define global variable with webpack

查看:272
本文介绍了使用webpack定义全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用webpack定义一个全局变量,结果如下:

Is it possible to define a global variable with webpack to result something like this:

var myvar = {};

我看到的所有例子都使用外部文件 require(进口? $ = jquery!。/ file.js)

All of the examples I saw were using external file require("imports?$=jquery!./file.js")

推荐答案

有几种方法可以接近全局:

There are several way to approach globals:

Webpack只评估模块一次,所以你的实例仍然是全局的,并且可以在模块之间进行更改。因此,如果您创建类似 globals.js 的内容并导出所有全局变量的对象,那么您可以导入'./globals'并读/写这些全局变量。您可以导入到一个模块中,从函数中更改对象并导入另一个模块并在函数中读取这些更改。还要记住顺序发生的事情。 Webpack将首先从 entry.js 开始接受所有导入并加载它们。然后它将执行 entry.js 。所以你读/写全局变量的地方很重要。它来自模块的根范围还是稍后调用的函数?

Webpack evaluates modules only once, so your instance remains global and carries changes through from module to module. So if you create something like a globals.js and export an object of all your globals then you can import './globals' and read/write to these globals. You can import into one module, make changes to the object from a function and import into another module and read those changes in a function. Also remember the order things happen. Webpack will first take all the imports and load them up in order starting in your entry.js. Then it will execute entry.js. So where you read/write to globals is important. Is it from the root scope of a module or in a function called later?

注意:如果您希望实例每次都 new ,那么请使用 ES6课程。传统上在JS中你可以大写类(而不是对象的小写),例如

从'./foo-bar'//< - 用法:myFooBar =导入FooBar new FooBar()

Note: If you want the instance to be new each time, then use an ES6 class. Traditionally in JS you would capitalize classes (as opposed to the lowercase for objects) like
import FooBar from './foo-bar' // <-- Usage: myFooBar = new FooBar()

以下是使用Webpack的ProvidePlugin(它使模块在每个模块中都可用作变量)的方法那些你实际使用它的模块)。当您不想一次又一次地从'foo'输入导入栏时,这非常有用。或者你可以在这里引入像jQuery或lodash这样的全局包(尽管你可以看看Webpack的外部)。

Here's how you can do it using Webpack's ProvidePlugin (which makes a module available as a variable in every module and only those modules where you actually use it). This is useful when you don't want to keep typing import Bar from 'foo' again and again. Or you can bring in a package like jQuery or lodash as global here (although you might take a look at Webpack's Externals).

步骤1)创建任何模块。例如,一组全局实用程序将非常方便:

Step 1) Create any module. For example, a global set of utilities would be handy:

utils.js

export function sayHello () {
  console.log('hello')
}

步骤2)别名模块并添加到ProvidePlugin:

Step 2) Alias the module and add to ProvidePlugin:

webpack.config.js

var webpack = require("webpack");
var path = require("path");

// ...

module.exports = {

  // ...

  resolve: {
    extensions: ['', '.js'],
    alias: {
      'utils': path.resolve(__dirname, './utils')  // <-- When you build or restart dev-server, you'll get an error if the path to your utils.js file is incorrect.
    }
  },

  plugins: [

    // ...

    new webpack.ProvidePlugin({
      'utils': 'utils'
    })
  ]  

}

现在只需在任何js文件中调用 utils.sayHello(),它应该可以工作。如果您正在使用Webpack,请确保重新启动您的开发服务器。

Now just call utils.sayHello() in any js file and it should work. Make sure you restart your dev-server if you are using that with Webpack.

注意:不要忘记告诉你的关于全球的信息,所以它不会抱怨。例如,请参阅我的在这里回答ESLint

如果你只想对你的全局变量使用const和字符串值,那么你可以将这个插件添加到你的Webpack插件列表中:

If you just want to use const with string values for your globals, then you can add this plugin to your list of Webpack plugins:

new webpack.DefinePlugin({
  PRODUCTION: JSON.stringify(true),
  VERSION: JSON.stringify("5fa3b9"),
  BROWSER_SUPPORTS_HTML5: true,
  TWO: "1+1",
  "typeof window": JSON.stringify("object")
})

使用它像:

console.log("Running App version " + VERSION);
if(!BROWSER_SUPPORTS_HTML5) require("html5shiv");



4)使用全局窗口对象(或Node的全局)



4) Use the global window object (or Node's global)

window.foo = 'bar'  // For SPA's, browser environment.
global.foo = 'bar'  // Webpack will automatically convert this to window if your project is targeted for web (default), read more here: https://webpack.js.org/configuration/node/

您会看到这通常用于polyfills,例如: window.Promise = Bluebird

You'll see this commonly used for polyfills, for example: window.Promise = Bluebird

(对于服务器端项目)dotenv软件包将采用本地配置文件(如果存在,您可以将其添加到.gitignore中任何密钥/凭证)并将配置变量添加到Node的 process.env 对象。

(For server side projects) The dotenv package will take a local configuration file (which you could add to your .gitignore if there are any keys/credentials) and adds your configuration variables to Node's process.env object.

// As early as possible in your application, require and configure dotenv.    
require('dotenv').config()

创建 .env 项目根目录中的文件。以 NAME = VALUE 的形式在新行上添加特定于环境的变量。例如:

Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

就是这样。

process.env 现在具有您在 .env 文件中定义的键和值。

process.env now has the keys and values you defined in your .env file.

var db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})



注意:



关于Webpack的 Externals ,请使用它您希望排除某些模块包含在构建的包中。 Webpack将使该模块在全球范围内可用,但不会将其放入您的捆绑包中。这对于像jQuery这样的大型库来说很方便(因为树摇动外部包在Webpack中不起作用)你已经在页面中加载了这些已经在单独的脚本标签中(可能来自CDN)。

Notes:

Regarding Webpack's Externals, use it if you want to exclude some modules from being included in your built bundle. Webpack will make the module globally available but won't put it in your bundle. This is handy for big libraries like jQuery (because tree shaking external packages doesn't work in Webpack) where you have these loaded on your page already in separate script tags (perhaps from a CDN).

这篇关于使用webpack定义全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆