如何配置babel以在不同环境中使用不同配置运行

时间:2016-01-21 13:01:37

标签: testing reactjs webpack babeljs

我想在我的react / redux应用程序中添加磁带测试。我找不到让我的应用程序同时用于测试和运行的方法。使用此.babelrc配置测试不会运行,但应用程序正常工作:

{
  "name": "add-projects",
  "version": "0.0.0",
  "description": "Add projects",
  "scripts": {
    "start": "node server.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/rackt/redux.git"
  },
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/rackt/redux/issues"
  },
  "homepage": "http://rackt.github.io/redux",
  "dependencies": {
    "immutable": "^3.7.6",
    "react": "^0.14.0",
    "react-dom": "^0.14.0",
    "react-redux": "^4.0.0",
    "redux": "^3.0.0",
    "redux-thunk": "^0.1.0",
    "redux-undo": "^0.5.0"
  },
  "devDependencies": {
    "babel-core": "^5.6.18",
    "babel-loader": "^5.1.4",
    "babel-plugin-react-transform": "^1.1.0",
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "babel-tape-runner": "^2.0.0",
    "enzyme": "^2.0.0-rc1",
    "expect": "^1.6.0",
    "express": "^4.13.3",
    "jsdom": "^7.2.2",
    "node-libs-browser": "^0.5.2",
    "react-addons-test-utils": "^0.14.6",
    "react-transform-hmr": "^1.0.0",
    "tape": "^4.4.0",
    "tape-run": "^2.1.2",
    "webpack": "^1.9.11",
    "webpack-dev-middleware": "^1.2.0",
    "webpack-hot-middleware": "^2.2.0"
  }
}

使用这个.babelrc配置测试工作正常,但是npm start会抛出错误:模块构建失败:ReferenceError:[BABEL]

var webpack = require('webpack')
var webpackDevMiddleware = require('webpack-dev-middleware')
var webpackHotMiddleware = require('webpack-hot-middleware')
var config = require('./webpack.config')

var app = new (require('express'))()
var port = 3000

var compiler = webpack(config)
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }))
app.use(webpackHotMiddleware(compiler))

app.get("/", function(req, res) {
  res.sendFile(__dirname + '/index.html')
})

app.listen(port, function(error) {
  if (error) {
    console.error(error)
  } else {
    console.info("==>   Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port)
  }
})

如何合并这两个文件,以便运行和测试都有效?

这是我的package.json:

var path = require('path')
var webpack = require('webpack')

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    './index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      loaders: ['babel'],
      exclude: /node_modules/,
      include: __dirname
    }]
  }
}


// When inside Redux repo, prefer src to compiled version.
// You can safely delete these lines in your project.
var reduxSrc = path.join(__dirname, '..', '..', 'src')
var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules')
var fs = require('fs')

if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) {
  // Resolve Redux to source
  module.exports.resolve = { alias: { 'redux': reduxSrc } }
  // Compile Redux from source
  module.exports.module.loaders.push({
    test: /\.js$/,
    loaders: ['babel'],
    include: reduxSrc
  })
}

这是server.js:

function addElement(element, doc, opt, newPage, callback) {
        var thiscreen = element;
        //Get the original background color.
        var originalBGColor = thiscreen.style.backgroundColor;
        //Change the background color of the element to desired color.
        if (opt.bgColor)
            thiscreen.style.backgroundColor = opt.bgColor;
        var options = options || {};
        options.elements = [thiscreen];
        //Increment the in-progress counter.
        counter++;
        console.log('adding' + counter);
        console.log(element);
        //The complete callback method.
        options.complete = setTimeout(function(images) {
            //Decrement the in-progress counter since the image is successfully generated..
            counter--;
            console.log('complete' + counter);
            console.log(element);
            var queue = html2canvas.Parse(thiscreen, images, options),
                canvas = html2canvas.Renderer(queue, options);
            //Reset the background color.
            thiscreen.style.backgroundColor = originalBGColor;
            //Add the generated image to PDF document.
            doc.addImage(canvas.toDataURL(), 'png', opt.x, opt.y, opt.width, opt.height);
            //Call the callback method if any
            if (callback) {
                callback();
            }
        }, 500);
        //Conver the html to PNG using html2canvas util.
        html2canvas.Preload(thiscreen, options);
    }

webpack.config.js:

SELECT * from wp_posts AS vender 
LEFT OUTER
JOIN wp_postmeta AS vender_campaign ON vender_campaign.meta_key = 'vender' 
  AND vender_campaign.meta_value LIKE CONCAT('%"',vender.ID,'"%')
WHERE vender.post_status = 'publish' AND vender.post_type = 'vender'

2 个答案:

答案 0 :(得分:31)

.babelrc

中设置不同的环境
{
  "env": {
    "dev": {
       "presets": ["es2015"],
       "plugins":["x"]
     },
    "test": {
      "presets": ["es2015"]
    }
  }
}

然后在设置babel

后运行BABEL_ENV

BABEL_ENV=test <commandhere>BABEL_ENV=dev <commandhere>

答案 1 :(得分:2)

这是基于当前NODE_ENV共享/更改配置的另一种方法:

package.json

"scripts": {
  "build": "NODE_ENV=production next build",
  "dev": "NODE_ENV=development next dev",
  "test" : "NODE_ENV=test jest"
   ...etc
}

babel.config.js (必须为.js文件)

const { NODE_ENV } = process.env;

const inProduction = NODE_ENV === "production";
const inDevevelopment = NODE_ENV === "development";

module.exports = api => {
  /* 
    alternatively, you can utilize api.env() to get the current NODE_ENV:
    const inProduction = api.env("production");
    const inDevevelopment = api.env("development");

    if using api.env(), then these must be defined before invoking the cache
  */
  api.cache.using(() => process.env.NODE_ENV);

  return {
    presets: ["next/babel"],
    plugins: [
      [
        "styled-components",
        {
          ssr: true,
          displayName: inDevevelopment,
          preprocess: inProduction,
        },
      ],
      ["import", { libraryName: "antd", libraryDirectory: "lib" }],
      inProduction && "react-remove-properties",
    ].filter(Boolean), // this will filter any falsy plugins (such as removing react-remove-properties when not in production)
  };
};