Webpack coffee-loader

2023-05-22 09:17 更新

Compile CoffeeScript to JavaScript.

起步

安裝 coffeescript 和 coffee-loader:

npm install --save-dev coffeescript coffee-loader

然后添加 plugin 到 webpack 配置文件. 例:

file.coffe

# 任務(wù):
number   = 42
opposite = true

# 條件:
number = -42 if opposite

# 函數(shù):
square = (x) -> x * x

# 數(shù)組:
list = [1, 2, 3, 4, 5]

# 對象:
math =
  root:   Math.sqrt
  square: square
  cube:   (x) -> x * square x

# Splats:
race = (winner, runners...) ->
  print winner, runners

# 存在性:
alert "I knew it!" if elvis?

# 數(shù)組推導(dǎo)(comprehensions):
cubes = (math.cube num for num in list)

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.coffee$/,
        loader: "coffee-loader",
      },
    ],
  },
};

替代方案:

import coffee from "coffee-loader!./file.coffee";

然后按偏好運(yùn)行 webpack

選項(xiàng)

類型:Object 默認(rèn):?{ bare: true }?

所有 coffeescript 選項(xiàng)的文檔 點(diǎn)擊查看.

transpile 選項(xiàng)的文檔 點(diǎn)擊查看.

?? sourceMap 選項(xiàng)從 compiler.devtool 中選取一個值作為默認(rèn)值。
?? filename 選項(xiàng)從 webpack loader API 中選取一個值。 選項(xiàng)值將被忽略。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.coffee$/,
        loader: "coffee-loader",
        options: {
          bare: false,
          transpile: {
            presets: ["@babel/env"],
          },
        },
      },
    ],
  },
};

示例

CoffeeScript 與 Babel

來自 CoffeeScript 2 的文檔:

CoffeeScript 2 使用最新的句法生成 JavaScript。 代碼運(yùn)行所在的運(yùn)行時或?yàn)g覽器有可能無法支持全部相關(guān)句法。 這種情況下,新的 JavaScript 句法將被轉(zhuǎn)換為舊的 JavaScript 句法,以便在較低版本 Node 環(huán)境或?yàn)g覽器中運(yùn)行這些代碼。比如將 ?{ a } = obj? 轉(zhuǎn)換為 ?a = obj.a?。 這個轉(zhuǎn)換的過程是由一些諸如 Babel, Bublé or Traceur Compiler 等轉(zhuǎn)換工具完成的。

安裝 @babel/core 和 @babel/preset-env 然后創(chuàng)建配置文件:

npm install --save-dev @babel/core @babel/preset-env
echo '{ "presets": ["@babel/env"] }' > .babelrc

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.coffee$/,
        loader: "coffee-loader",
        options: {
          transpile: {
            presets: ["@babel/env"],
          },
        },
      },
    ],
  },
};

Literate CoffeeScript

開啟 Literate CoffeeScript 時需要設(shè)置:

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.coffee$/,
        loader: "coffee-loader",
        options: {
          literate: true,
        },
      },
    ],
  },
};

貢獻(xiàn)

如果您尚未了解,建議您閱讀以下貢獻(xiàn)指引。

CONTRIBUTING

許可

MIT


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號