如何导入从webpack.config生成的javascript导出文件?

时间:2017-06-06 15:46:16

标签: javascript node.js import npm webpack

问题描述

我需要设置DEV或Production环境,以便我可以在本地测试API,或者让它们为生产做好准备。

即:使用http://localhost/api/app/login/api/app/login

现在我可以通过将NODE_ENV变量附加到package.json中的npm脚本和我的webpack.config中的几行代码来实现此目的:

"scripts": {
    "dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
    "prod": "NODE_ENV=production webpack-dev-server -p",

webpack.config

const environment = process.env.NODE_ENV;
....
new CopyWebpackPlugin([{ from: "static" }])

^将创建一个我可以在services/api.js文件中使用的env。 现在我的问题是我的Jest测试每次都会失败,因为env未定义。

尝试解决方案 - 需要帮助

所以现在我尝试做的是使用node实际生成一个Javascript文件,我可以直接导入到我的services/api.js中,这样我就可以避免出现未定义的env错误测试

我能够使用以下对webpack.config的更新创建一个Javascript文件

const fs = require('fs');
const webpack = require('webpack')
const environment = process.env.NODE_ENV;

// fs.writeFileSync('src/consts/env.txt', environment);

const stream = fs.createWriteStream("src/consts/endpoints.js");
stream.once('open', function(fd) {
  stream.write('export const environment = () => "'+environment+'"');
  stream.end();
});

它创建的文件(src / consts / endpoints.js):

export const environment = () => "development"

我也尝试过这种方式:

export const environment = "development"

现在我更新了 services/api.js

import axios from 'axios'
import environment from '../consts/endpoints'
console.log('api.js environment:', environment);

但是当我查看localhost时,环境是未定义的。 enter image description here

如何解决此问题?这是竞争条件吗?是否有另一种方法来生成我需要导入的文件?

我尝试生成.txt文件但是我无法在本地导入该文件,只能在云中执行。

完整的webpack.config文件

const fs = require('fs');
const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const environment = process.env.NODE_ENV;

// fs.writeFileSync('src/consts/env.txt', environment);

const stream = fs.createWriteStream("src/services/environment.js");
stream.once('open', function(fd) {
  stream.write('export const environment = "'+environment+'"');
  stream.end();
});

module.exports = {
  context: src,
  entry: [
    "./index.js"
  ],
  output: {
    path: dist,
    filename: "manage2.bundle.js",
    publicPath: '/static/',
  },
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: ["babel-loader"]
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallbackLoader: "style-loader",
          loader: ["css-loader", "sass-loader"],
          publicPath: dist
        })
      }
    ]
  },
  devServer: {
    hot: false,
    quiet: true,
    publicPath: "",
    contentBase: path.join(__dirname, "dist"),
    compress: true,
    stats: "errors-only",
    open: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "index.html"
    }),
    new ExtractTextPlugin({
      filename: "manage2.css",
      disable: false,
      allChunks: true
    }),
    new CopyWebpackPlugin([{ from: "static" }])
  ]
};
// new webpack.DefinePlugin({ env: JSON.stringify(environment) })

1 个答案:

答案 0 :(得分:0)

想出来了!

我导入的文件不正确。

所以来自 webpack.config

const environment = process.env.NODE_ENV;

const stream = fs.createWriteStream("src/services/environment.js");
stream.once('open', function(fd) {
  stream.write('const env = "'+environment+'"\n');
  stream.write('export default env');
  stream.end();
});

^生成此文件( src / services / environment.js ),其中包含:

const env = "development"
export default env

最后在我的 services / api.js 文件中,我可以按照我想要的方式使用import语句,我错过了上面的export default

import axios from 'axios'
import endpoints from './endpoints'
import env from './environment'

const api = endpoints(env);
console.log('api', api);

const log = (method, err) => {
    console.error(`%c${method}`, 'background: #393939; color: #F25A43', err);
    return err;
};

export const userLogin = (username, password) => {
    const post_data = { username, password };
    return axios.post(api.login, post_data)
        .then(res => res)
        .catch((err) => log('api.userLogin', err));
};

在我的package.json中,我可以更改ENV var以吐出"development""production"

"scripts": {
    "dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
    "prod": "NODE_ENV=production webpack-dev-server -p",