Any way to use webpack to load a resource at runtime?

前端 未结 3 1122
深忆病人
深忆病人 2020-12-28 15:07

I have a single .json file that contains configuration stuff that I would like to reference from another script file using the typical import/require syntax. Currently I\'m

3条回答
  •  太阳男子
    2020-12-28 15:44

    I had the same case with a file (config.json).

    I decided to copy it with Copy-Webpack-Plugin

    new CopyWebpackPlugin([
        // Copy directory contents to {output}/
        { from: 'config.json' }
      ]) 
    

    After that, my file was in the output build directory. I used 'externals' property to reference my file in my webpack.config file :

      externals: {
        'config': "require('./config.json')"
      }
    

    In my js file which load the config.json :

    import config from 'config'
    

    'config' load require('./config.json) which is the one in the output build directory.

    I know it's tricky but I didn't find another solution to my problem. Maybe it will help someone.

    EDIT

    I had to use webpack in order to build because import config from 'config' wasn't understandable without it. That's why I replace :

    externals: {
        './config.json': "require('./config.json')"
      }
    

    and

    var config = require('./config.json') //replace import config from 'config'
    

    Without webpack, Javascript understand var config = require('./config.json') because it's the right path.

    And when I build with webpack, it change by require('./config.json') when it sees './config.json', so it works

提交回复
热议问题