Skip to content

How to add new definitions to webpack.DefinePlugin? #1647

Closed

Description

@pendenaor

Version

3.0.0-rc.3

Reproduction link

https://gist.github.com/pendenaor/591d5ffb3af4edbe640d20abeb8d999d

Steps to reproduce

  1. create an app with vue-cli 3 rc3
  2. copy App.vue and vue.config.js
  3. Run the app

What is expected?

jQuery and lodash are available

What is actually happening?

jQuery and lodash are 'undefined'


inspect command output

...
  plugins: [
    /* config.plugin('vue-loader') */
    new VueLoaderPlugin(),
    /* config.plugin('define') */
    new DefinePlugin(
      {
        'process.env': {
          NODE_ENV: '"development"',
          VUE_APP_CLI_UI_URL: '""',
          BASE_URL: '"/"'
        }
      }
    ),
    /* config.plugin('case-sensitive-paths') */
    new CaseSensitivePathsPlugin(),
    /* config.plugin('friendly-errors') */
    new FriendlyErrorsWebpackPlugin(
      {
        additionalTransformers: [
          function () { /* omitted long function */ }
        ],
        additionalFormatters: [
          function () { /* omitted long function */ }
        ]
      }
    ),
    /* config.plugin('hmr') */
    new HotModuleReplacementPlugin(),
    /* config.plugin('no-emit-on-errors') */
    new NoEmitOnErrorsPlugin(),
    /* config.plugin('progress') */
    new ProgressPlugin(),
    /* config.plugin('html') */
    new HtmlWebpackPlugin(
      {
        templateParameters: function () { /* omitted long function */ },
        template: 'C:\\Public\\Repo\\new-vue-cli\\sinoc_ui\\public\\index.html'
      }
    ),
    /* config.plugin('preload') */
    new PreloadPlugin(
      {
        rel: 'preload',
        include: 'initial',
        fileBlacklist: [
          /\.map$/,
          /hot-update\.js$/
        ]
      }
    ),
    /* config.plugin('prefetch') */
    new PreloadPlugin(
      {
        rel: 'prefetch',
        include: 'asyncChunks'
      }
    ),
    /* config.plugin('copy') */
    new CopyWebpackPlugin(
      [
        {
          from: 'C:\\Public\\Repo\\new-vue-cli\\sinoc_ui\\public',
          to: 'C:\\Public\\Repo\\new-vue-cli\\sinoc_ui\\dist',
          ignore: [
            'index.html',
            '.DS_Store'
          ]
        }
      ]
    ),
    {
      definitions: {
        $: 'jquery',
        jquery: 'jquery',
        'window.jQuery': 'jquery',
        jQuery: 'jquery',
        _: 'lodash'
      }
    }
  ],
...

Activity

  1. pendenaor commented on Jun 21, 2018

    @pendenaor
    Author

    found a way:

    const webpack = require('webpack')
    
    module.exports = {
      chainWebpack: config => {
        config.plugin('define').tap(definitions => {
          definitions[0] = Object.assign(definitions[0], {
            $: 'jquery',
            jquery: 'jquery',
            'window.jQuery': 'jquery',
            jQuery: 'jquery',
            _: 'lodash'
          })
          return definitions
        })
      }
    }
    
  2. pedroresende commented on Jun 25, 2018

    @pedroresende

    @pendenaor I have a question, about this. Were you obliged to have import $ from "jquery"; in the <script> inside every vue file you wanted to use ? Did you add anything else to .eslintrc.js ?

  3. pendenaor commented on Jun 26, 2018

    @pendenaor
    Author

    I import jquery in my main.js. I didn't have .eslintrc.js, but in my package.json, i add these lines :

    "eslintConfig": {
    ...
        "globals": {
          "$": false,
          "jQuery": false,
          "module": false,
          "logger": false
    ...
    
  4. pedroresende commented on Jun 26, 2018

    @pedroresende

    @pendenaor Thanks, however I can't make it to work ... I've added in main.js the import jquery (https://github.com/pedroresende/vue-experience/blob/master/src/main.js#L6) and I'm trying to use it in the Home.vue (https://github.com/pedroresende/vue-experience/blob/master/src/views/Home.vue#L18)

  5. pedroresende commented on Jun 26, 2018

    @pedroresende

    @pendenaor Thanks, finally found the problem. It seems that I have to define jquery globally

    window.$ = window.jQuery = window.jquery = require("jquery");
    
  6. francoismassart commented on Feb 1, 2019

    @francoismassart

    This topic was useful!

    I was trying to inject the semver version string from my package.json during the build process of my Vue app.

    Here is how I injected this info via vue.config.js

    module.exports = {
      chainWebpack: (config) => {
        config.plugin('define').tap((definitions) => {
          definitions[0]['process.env']['PACKAGE_VERSION'] = JSON.stringify(require('./package.json').version);
          return definitions;
        });
      }
    }

    Then inside my sources in Vue: process.env.PACKAGE_VERSION 🥇

  7. AndreiSoroka commented on Sep 22, 2019

    @AndreiSoroka
    Contributor

    @francoismassart
    file vue.config.js:

    process.env.VUE_APP_VERSION = require('./package.json').version
    
    module.exports = {
      // config
    }

    from: #1904 (comment)

  8. ortonomy commented on Jan 7, 2021

    @ortonomy

    @AndreiSoroka -- perfect, exactly what I was looking for.

  9. vegerot commented on Mar 18, 2021

    @vegerot
    Contributor

    This topic was useful!

    I was trying to inject the semver version string from my package.json during the build process of my Vue app.

    Here is how I injected this info via vue.config.js

    module.exports = {
      chainWebpack: (config) => {
        config.plugin('define').tap((definitions) => {
          definitions[0]['process.env']['PACKAGE_VERSION'] = JSON.stringify(require('./package.json').version);
          return definitions;
        });
      }
    }

    Then inside my sources in Vue: process.env.PACKAGE_VERSION 🥇

    @francoismassart @AndreiSoroka

    This is very helpful. I was wondering how I can do something similar, but with an async function.

    I want to get the git commit for diagnostic messages and Vuex.version. The way I was thinking of doing it would be something like

    const util = require('util');
    const exec = util.promisify(require('child_process').exec);
    
    {
    chainWebpack: (config) => {
        config.plugin('define').tap(async (definitions) => {
          console.log({ definitions }, definitions);
          definitions[0]['process.env'].PACKAGE_VERSION =
            JSON.stringify((await exec('git describe')).stdout);
          return definitions;
        });
      }
    }

    or

      configureWebpack: async (config) => {
        config.plugins.push(
          new webpack.DefinePlugin({
            VERSION: JSON.stringify((await exec('git describe')).stdout),
          }),
        );
      },

    Then have something like

    export default new Vuex.Store<RootState>({
      modules: {
        // my modules
      },
      state: {
        version: process.env.PACKAGE_VERSION,
      } as any,
    });

    or

    export default new Vuex.Store<RootState>({
      modules: {
        // my modules
      },
      state: {
        version: VERSION,
      } as any,
    });

    So, how can I get that to work with something async? Just setting it to be async doesn't seem to work.

    Any other way to get git command output into buildtime?

  10. fangbinwei commented on Mar 19, 2021

    @fangbinwei
    Collaborator
  11. vegerot commented on Mar 19, 2021

    @vegerot
    Contributor

    @vegerot workaround #3328 (comment)

    I actually made my own workaround. I just used execSync instead

        const version = execSync('git describe', { encoding: 'utf-8' })
          .trim();
  12. Keavon commented on Dec 16, 2021

    @Keavon

    @francoismassart file vue.config.js:

    process.env.VUE_APP_VERSION = require('./package.json').version
    
    module.exports = {
      // config
    }

    from: #1904 (comment)

    In case anyone's running across this like I did: the VUE_APP_ prefix is required (at least in Vue 3).

    And if your .vue file's JS doesn't know what the variable process is, you may need to add "node" to "compilerOptions": { "types": ["node"] } in your tsconfig.json.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions