How to access webpack config variable in other js file

会有一股神秘感。 提交于 2021-02-11 12:38:10

问题


I am running following command to run the app locally

npm run start

package.json

...
"scripts": {
    "start": "concurrently --kill-others --kill-others-on-fail -p name --names \"config\" \"npm run start:config\"",
    "build": "npm run build:config",
    "build:config": "webpack --config ./webpack.config.config.js -p",
    "start:config": "webpack-dev-server --config ./webpack.config.config.dev.js --port 4200"
  },
...

I am trying to access env mode in scripts.js defined in webpack config js as shown below But I am getting following error:

Uncaught SyntaxError: The requested module '../webpack.config.config.dev.js' does not provide an export named 'mode'

scripts.js

import { mode } from '../webpack.config.config.dev.js';
// error: Uncaught SyntaxError: The requested module '../webpack.config.config.dev.js' does not provide an export named 'mode'

var process = function() {
   let url = config.mode == 'development' ? 'local-url' : 'url';
}

webpack.config.config.dev.js

...
const config = require('./webpack.config.config.js');
config.devServer = {
  contentBase: './build',
  historyApiFallback: true,
  headers: {
    "Access-Control-Allow-Origin": "*",
  },
  proxy: {
    "/common/": {
      pathRewrite: {"^/common" : ""}
    }
  }
}

config.mode = 'development'
module.exports = config;

webpack.config.config.js

    const webpack = require('webpack')
    const path = require('path');
    const CleanWebpackPlugin = require('clean-webpack-plugin');
    const CopyWebpackPlugin = require('copy-webpack-plugin');
    
    module.exports = {
      entry: './src/scripts/config.js',
      output: {
        filename: 'config.js',
        library: 'config',
        libraryTarget: 'amd',
        path: path.resolve(__dirname, 'build'),
      },
      mode: 'production',
      module: {
        rules: [
 ...      },
      resolve: {
        modules: [
          __dirname,
          'node_modules', 
        ],
      },
      plugins: [
        CopyWebpackPlugin([
          {from: path.resolve(__dirname, 'src/index.html')},
          {from: path.resolve(__dirname, 'src/styles.css')},
          {from: path.resolve(__dirname, 'src/scripts'), to: path.resolve(__dirname, './build/scripts'), force: true },
          {from: path.resolve(__dirname, 'webpack.config.config.dev.js'), to: path.resolve(__dirname, './build/webpack.config.config.dev.js'), force: true }
        ]),
        new CleanWebpackPlugin(['build']),
      ],
      devtool: 'source-map',
      externals: [
        /^lodash$/,
        /^rxjs\/?.*$/,
      ],
    };

index.html

...
<script src="scripts/scripts.js" type="module"></script>
...

来源:https://stackoverflow.com/questions/65989697/how-to-access-webpack-config-variable-in-other-js-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!