简体   繁体   中英

How to use webpack CLI output a module which can be imported?

There are three files here.

file 1: src/module/a/index.js

import b from './b.js'; 
import c from '../c/index.js'; 

const d = () => 'd'; 

export default { b, c, d }; 

file 2: src/module/a/b.js

export default () => 'b'; 

file 3: src/module/c/index.js

export default () => 'c' 

I want to use the webpack CLI to package the code into a file.

// file dist/lib/a.js 
const b = () => 'b'; 
const c = () => 'c'; 
const d = () => 'd'; 

export default { b, c, d }; 

Because you are using ES6 code, you will need transpiler like babel, to do so you need a webpack.config.js file in your root directory.

Here is minimal setup for you webpack.config.js

const path = require('path');

const config = {
  entry: './src/index.js', // path to your index.js
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'bundle.js', // output file
    publicPath: 'build/' // output dir
  },
  module: {
    rules: [
      {
        use: 'babel-loader',
        test: /\.js$/
      }
    ]
  }
};

module.exports = config;

Here is your minimal package.json file

Add your script, you can run it later via npm run build command

"scripts": {
  "build": "webpack"
},

Add your dev dependencies, you can later install it using npm install , or just install it separately using command

npm i --save-dev babel-core babel-loader babel-preset-env webpack

"devDependencies": {
    "babel-core": "^6.21.0",
    "babel-loader": "^6.2.10",
    "babel-preset-env": "^1.1.4",
    "webpack": "^2.2.0-rc.0"
}

Depending on your needs you can later add other babel presets, like es2015 and stage-0

npm install --save-dev babel-preset-es2015
npm install --save-dev babel-preset-stage-0

Now add .babelrc file into your root directory, paste this code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM