如何配置 babel 在不同的环境下以不同的配置运行

Posted

技术标签:

【中文标题】如何配置 babel 在不同的环境下以不同的配置运行【英文标题】:How do you configure babel to run with different configurations in different environments 【发布时间】:2016-04-27 17:56:11 【问题描述】:

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


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

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


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

如何合并这两个文件以便运行和测试都可以工作?

这是我的 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"
  

这里是 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
  )

【问题讨论】:

这里有一个little example 用于 testem+tape。也许这有帮助。在这种情况下,我会自己设置一个单独的测试目标。 【参考方案1】:

在你的.babelrc中设置不同的环境


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

然后在你设置好BABEL_ENV之后运行babel

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

如果不设置BABEL_ENV,babel 将使用NODE_ENV 的值。 如果您既不设置BABEL_ENV 也不设置NODE_ENV,它将使用“开发”。

代码如下:

function getEnv(defaultValue = "development") 
  return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue;

【讨论】:

无法与 babel loader 7、babel core 6、webpack/dev-server 2 一起使用 这是唯一的方法。如果你认为你应该能够将不同的配置文件传递给 babel CLI,在我看来这将是一个不那么模糊的解决方案,babel 明确不支持这样做:见这个问题github.com/babel/babel/issues/4970 这对我有用。我正在使用 mocha 和 rollup,它们对 modules 选项有冲突的要求,所以我需要添加一个“测试”环境。谢谢! 我想要一个特定的配置来运行测试用例。因此,我没有添加开发和测试环境,而是移动了写在“dev”下的预设,就像通常我们写预设一样,并且在“env”中只有“test”。因此,实际上,在 BABEL_ENV=test 中,它会覆盖默认值。【参考方案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 inDevelopment = NODE_ENV === "development";

module.exports = api => 
  /* 
    alternatively, you can utilize api.env() to get the current NODE_ENV:
    const inProduction = api.env("production");
    const inDevelopment = 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",
        
          s-s-r: true,
          displayName: inDevelopment,
          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)
  ;
;

【讨论】:

这正是我想要的,谢谢!

以上是关于如何配置 babel 在不同的环境下以不同的配置运行的主要内容,如果未能解决你的问题,请参考以下文章

使用virtualBox在CentOS6.5环境下以桥接方式配置网络

用开源自动化运维工具 SaltStack 在云平台中实现各主机统一配置管理

如何用开源自动化运维工具 SaltStack 在云平台中实现各主机统一配置管理

如何实现根据环境切换不同配置?

如何使用 babel

如何在 Angular 中为不同的环境设置配置或属性文件?