Programming

웹팩으로 전역 변수 정의

procodes 2020. 7. 26. 13:21
반응형

웹팩으로 전역 변수 정의


webpack으로 전역 변수를 정의하여 다음과 같은 결과를 얻을 수 있습니까?

var myvar = {};

내가 본 모든 예제는 외부 파일을 사용하고있었습니다. require("imports?$=jquery!./file.js")


세계에 접근하는 방법에는 여러 가지가 있습니다.

1) 변수를 모듈에 넣습니다.

Webpack은 모듈을 한 번만 평가하므로 인스턴스는 전역으로 유지되며 모듈 간 변경 사항이 적용됩니다. 따라서 a globals.js같은 것을 만들고 모든 전역의 객체를 내 보내면 import './globals'이러한 전역에 읽고 쓸 수 있습니다 . 한 모듈로 가져 와서 함수에서 객체를 변경하고 다른 모듈로 가져 와서 함수의 변경 사항을 읽을 수 있습니다. 또한 일이 일어나는 순서를 기억하십시오. Webpack은 먼저 모든 가져 오기를 수행하여에서 시작하는 순서대로로드합니다 entry.js. 그런 다음 실행 entry.js됩니다. 따라서 전역에 대한 읽기 / 쓰기가 중요합니다. 모듈의 루트 범위 또는 나중에 호출되는 함수에 있습니까?

참고 : new매번 인스턴스를 사용하려면 ES6 클래스 를 사용하십시오 . 전통적으로 JS에서는 다음과 같이 클래스를 대문자로 사용합니다 (객체의 소문자가 아닌).
import FooBar from './foo-bar' // <-- Usage: myFooBar = new FooBar()

2) 웹팩의 ProvidePlugin

다음은 Webpack의 ProvidePlugin을 사용하여 수행 할 수있는 방법입니다 (모든 모듈에서 모듈로 변수로 사용 가능하고 실제로 사용하는 모듈에서만 가능). 이것은 계속 타이핑을 계속하고 싶지 않을 때 유용 import Bar from 'foo'합니다. 또는 jQuery 또는 lodash와 같은 패키지를 전역으로 가져올 수 있습니다 (Webpack의 Externals를 볼 수도 있지만 ).

1 단계) 모듈을 만듭니다. 예를 들어, 전역 유틸리티 세트가 유용합니다.

utils.js

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

2 단계) 모듈 별명을 지정하고 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'
    })
  ]  

}

이제 utils.sayHello()모든 js 파일을 호출 하면 작동합니다. Webpack과 함께 사용하는 경우 dev 서버를 다시 시작하십시오.

참고 : 린터에 글로벌 정보를 알려주는 것을 잊지 마십시오. 예를 들어 ESLint에 대한 내 대답은 여기를 참조하십시오 .

3) Webpack의 DefinePlugin 사용

전역에 문자열 값과 함께 const를 사용하려면 Webpack 플러그인 목록에이 플러그인을 추가 할 수 있습니다.

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) 전역 창 객체 (또는 노드의 전역)를 사용하십시오.

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/

예를 들어 폴리 필에 일반적으로 사용되는 것을 볼 수 있습니다. window.Promise = Bluebird

5) dotenv 와 같은 패키지를 사용하십시오.

(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()

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

That's it.

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
})

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).


I was about to ask the very same question. After searching a bit further and decyphering part of webpack's documentation I think that what you want is the output.library and output.libraryTarget in the webpack.config.js file.

For example:

js/index.js:

var foo = 3;
var bar = true;

webpack.config.js

module.exports = {
   ...
   entry: './js/index.js',
   output: {
      path: './www/js/',
      filename: 'index.js',
      library: 'myLibrary',
      libraryTarget: 'var'
   ...
}

Now if you link the generated www/js/index.js file in a html script tag you can access to myLibrary.foo from anywhere in your other scripts.


Use DefinePlugin.

The DefinePlugin allows you to create global constants which can be configured at compile time.

new webpack.DefinePlugin(definitions)

Example:

plugins: [
  new webpack.DefinePlugin({
    PRODUCTION: JSON.stringify(true)
  })
  //...
]

Usage:

console.log(`Environment is in production: ${PRODUCTION}`);

You can use define window.myvar = {}. When you want to use it, you can use like window.myvar = 1


I solved this issue by setting the global variables as a static properties on the classes to which they are most relevant. In ES5 it looks like this:

var Foo = function(){...};
Foo.globalVar = {};

참고URL : https://stackoverflow.com/questions/37656592/define-global-variable-with-webpack

반응형