webpack從零開始第3課: 作爲node的一個模塊來使用

webpack目錄node

參考: https://webpack.js.org/api/node/webpack

更多的時間,咱們將webpack作爲一個nodejs模塊來使用web

一:新建本身的打包文件build.js

咱們在./build/新建一個文件 build.js,內容以下npm

const webpack = require('webpack')
const webpackConfig = require('./webpackfile.js');
webpack(webpackConfig, (err, stats) => {
  if (err) throw err
  console.log('已打包好了,咱們作點別的事')
})

打包segmentfault

D:\03www2018\study\webpack2017>node ./build/build.js

效果與執行webpack命令同樣
寫成npm srciptapi

"scripts": {
    "abc": "webpack --config ./build/webpackfile.js",
    "def": "webpack-dev-server",
    "tttt": "node build/build.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

執行
D:03www2018studywebpack2017>npm run ttttwebpack-dev-server

二:使用webpack編譯器ui

/*const webpack = require('webpack')
const webpackConfig = require('./webpackfile.js');
webpack(webpackConfig, (err, stats) => {
  if (err) throw err
  console.log('已打包好了,咱們作點別的事')
})*/

const webpack = require('webpack')
const webpackConfig = require('./webpackfile.js');
const compiler = webpack(webpackConfig)
compiler.run( (err, stats) => {
  if (err) throw err
  console.log('已打包好了,咱們作點別的事...')
})
// 編譯器運行比上面要快些,但它沒有包括watch部分,沒有監視,只是編譯

既監視又編譯webpack2

/*const webpack = require('webpack')
const webpackConfig = require('./webpackfile.js');
webpack(webpackConfig, (err, stats) => {
  if (err) throw err
  console.log('已打包好了,咱們作點別的事')
})*/

/*const webpack = require('webpack')
const webpackConfig = require('./webpackfile.js');
const compiler = webpack(webpackConfig)
compiler.run( (err, stats) => {
  if (err) throw err
  console.log('已打包好了,咱們作點別的事...')
})*/
// 編譯器運行比上面要快些,但它沒有包括watch部分,沒有監視,只是編譯,若是要編譯,還要加上


const webpack = require('webpack')
const webpackConfig = require('./webpackfile.js');
const compiler = webpack(webpackConfig)
const watching = compiler.watch({
  /* watchOptions */
}, (err, stats) => {
  // Print watch/build result here...
  console.log('我一直在監視着呢');
});

三:配合其它node模塊
上面的打包不夠豐富,若是和其它node模塊配置能夠實現更多的功能
如,使用chalk模塊來更好的顯示提示信息插件

相關文章
相關標籤/搜索