>[success] # DefinePlugin 注入全局成员 1. `DefinePlugin`允许在编译时创建配置的全局常量,是一个`webpack`内置的插件(不需要单独安装) 2. 在项经常有一个场景需要我们对一些全局通用的变量进行注册,例如有一个全局的`base_url` 可以利用Webpack 全局提供 3. `DefinePlugin`为代码注入全局成员,production模式下默认启动并插`process.env_NODE_ENV`常量 >[info] ## 使用 ~~~ // 单独使用需要引入webpack插件 const { DefinePlugin } = require("webpack") module.exports = { mode: 'none', entry: './src/main.js', output: { filename: 'bundle.js' }, plugins: [ // 键值会被注入代码中 作用 注入动态变化值 new DefinePlugin({ // 值要求的是一个代码片段 JS代码 或者js字符串表现形式"'https://api.example.com'" API_BASE_URL: JSON.stringify('https://api.example.com'), BASE_URL: "'./'" }) ] } ~~~ * 使用 ~~~ // src/main.js console.log(API_BASE_URL) // console.log("https://api.example.com") ~~~ * 编译template就可以正确的编译了,会读取到`BASE_URL`的值 ~~~html <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <title><%= htmlWebpackPlugin.options.title %></title> </head> <body> <noscript> <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <!-- built files will be auto injected --> </body> </html> ~~~