4

vue.js webpack problem: I can't add a plugin to vue.config.js with configureWebpack

I created a vue.js project with vue cli 3. I am following the example in: https://cli.vuejs.org/guide/webpack.html

My vue.config.js:

let webpack = require('webpack');

module.exports = {

    configureWebpack: {
        plugins: [
            new webpack.DefinePlugin({
                __TEST_MESSAGE__: JSON.stringify('howdy there!')
            })
        ]
    },
};

The resolved webpack config looks like:

{
    mode: 'production',
    ...
    plugins: [
        /* config.plugin('vue-loader') */
        new VueLoaderPlugin(),

        /* config.plugin('define') */
        new DefinePlugin(
          {
            'process.env': {
              VUE_APP_CLI_UI_URL: '""',
              NODE_ENV: '"production"',
              BASE_URL: '"/"'
            }
          }
        ),
        /* config.plugin('case-sensitive-paths') */
        new CaseSensitivePathsPlugin(),

        ...
        /////////////////////////////////////////////////////
        // Inserted note for SO: This is messed up!  Should
        // be: 
        // new DefinePlugin({ __TEST_MESSAGE__: '"howdy there!"' })
        /////////////////////////////////////////////////////
        {
          definitions: {
            __TEST_MESSAGE__: '"howdy there!"'
          }
        }
    ],
    ...
}

configureWebPack is supposed to merge my plugins with the vue defined plugins. Why is it stripping the DefinePlugin class out and just including the argument to the constructor in the plugins array?

1 Answer 1

5

Because Vue already includes the DefinePlugin, you need to modify it using Webpack's chain API instead of attempting to add a new one.

module.exports = {
  chainWebpack: config => {
    config.plugin('define').tap(args => {
      args[0].__TEST_MESSAGE__ = JSON.stringify('howdy there!')
      return args
    })
  }
}

This results in the following config (just an example)...

new DefinePlugin(
  {
    'process.env': {
      NODE_ENV: '"development"',
      BASE_URL: '"/"'
    },
    __TEST_MESSAGE__: '"howdy there!"'
  }
),

See https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-plugin

Sign up to request clarification or add additional context in comments.

6 Comments

Perfect. Thank you.
@jingleheimer you're very welcome. Thank you for asking a good question with lots of detail.
@phil how can I access TEST_MESSAGE in my component?
@daniel I believe it should be available as a global variable, just like process.env
@Phil thanks for your answer but I got "TS2304 Cannot find name : TEST_MESSAGE" (I'm usign vue&TS if its matter) when I assign as private items = TEST_MESSAGE;
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.