web-dev-qa-db-fra.com

Comment configurer babel pour qu'il s'exécute avec différentes configurations dans différents environnements

Je veux ajouter un test de bande à mon application react/redux. Je n'arrive pas à trouver un moyen pour que mon application fonctionne à la fois pour les tests et l'exécution. Avec ce .babelrc, les tests de configuration ne s'exécutent pas mais l'application fonctionne correctement:

{
  "stage": 2,
  "env": {
    "development": {
      "plugins": [
        "react-transform"
      ],
      "extra": {
        "react-transform": {
          "transforms": [{
            "transform": "react-transform-hmr",
            "imports": ["react"],
            "locals":  ["module"]
          }]
        }
      }
    }
  }
}

Avec ce .babelrc, les tests de configuration fonctionnent correctement mais le démarrage de npm génère une erreur: échec de la construction du module: ReferenceError: [BABEL]

{
  "presets": ["es2015", "react"]
}

Comment fusionner ces deux fichiers pour que l'exécution et les tests fonctionnent?

Voici mon package.json:

{
  "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"
  }
}

Voici le server.js:

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)
  }
})

webpack.config.js:

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
  })
}
21

Configurez différents environnements dans votre .babelrc

{
  "env": {
    "dev": {
       "presets": ["es2015"],
       "plugins":["x"]
     },
    "test": {
      "presets": ["es2015"]
    }
  }
}

Et puis exécutez babel après avoir défini votre BABEL_ENV

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

39
jhamm

Voici une approche alternative pour partager/alterner des configurations basées sur le courant 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 (doit être un .js fichier)

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)
  };
};
0
Matt Carlotta