kurodakazumichi / issues

0 stars 0 forks source link

【Babel + Webpack】自作jsライブラリを作る環境構築 #50

Open kurodakazumichi opened 6 years ago

kurodakazumichi commented 6 years ago

Babel + Webpackで自作のjsライブラリを作成するための環境を構築する

kurodakazumichi commented 6 years ago

最終的なフォルダ構成

root
 ┣ dist  ... 出力先
 ┃ ┣ index.html
 ┃ ┗ main.js
 ┣ src  ... ソースコード
 ┃ ┗ index.js
 ┣ webpack.config.js  ... webpackの設定
 ┣ .babelrc  ... babelの設定
 ┗ package.json  ... 依存関係やスクリプトの定義

準備

yarn init
yarn add -D webpack webpack-cli webpack-dev-server babel-loader @babel/core @babel/preset-env

npm

kurodakazumichi commented 6 years ago

package.json

{
  "name": "sample",
  "version": "1.0.0",
  "main": "index.js",
  "node": "v10.9.0",
  "npm": "6.2.0",
  "yarn": "1.9.4",
  "scripts": {
    "start": "webpack-dev-server",
    "build": "webpack --config webpack.config.js"
  },
  "devDependencies": {
    "@babel/core": "^7.1.6",
    "@babel/preset-env": "^7.1.6",
    "babel-loader": "^8.0.4",
    "webpack": "^4.26.0",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "^3.1.10"
  }
}

webpack--configオプションを指定すれば使用するconfigを指定できるので 開発用と本番用で設定分ければ良さそう。

.babelrc

{
  "presets": ["@babel/preset-env"]
}

最新のJS構文を使えるようにPresetを設定。

webpack.config.js

module.exports = {
  mode: 'development',
  entry : './src/index.js',
  output: {
    path    : `${__dirname}/dist`,
    filename: 'main.js'
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      }
    ]
  },
  devServer: {
    contentBase: './dist',
    open: true,
  }
};