Skill points used

  • vue2
  • webpack
  • NW.js
  • Node.js

One, foreword

Let me tell you a little bit about the origin of this project. Our company wants a new product, which is oriented to the field of education. It requires rapid development and must be compatible with XP, so WE choose Nw.js as the desktop client. At the same time, on the front wheels, vuejS has been tried to be applied to user-facing businesses. In this process, also stepped on some pits, also learned some new tips, share out for everyone’s reference.

Some students asked, why not just publish a complete project? I think I’ll get a lazy Seed package when WebPack finishes updating WebPack 2

Ii. Vue&webpack project construction

First use vuE-CLI to quickly build a Webpack template project, save worry and trouble. I won’t go into this too much, it’s easy. Convenient new understanding and learning, to a reference link github.com/vuejs-templ…

Third, the construction of Nw.js

The entire nw build is based on the project as a precursor to the vue&webpack. All right, here we go.

1. Install nw.js with NPM first

1) Can climb the wall smoothly

Nw.js developers provide NWJS/NPm-Installer if your Internet speed is good, it can be directly

npm install nw --nwjs_build_type=sdk --saveCopy the code

2) The Internet is not very good

Of course, my network situation is not very good, 233333 at this time can first download the NW SDK package to the local, the wall address: dl.nwjs. IO /v0.20.1/ NWJ… (Up to now, the latest SDK version is 0.20.1, and the system environment is Win10 X64.) Of course, as an old driver, I also have an unavoidable responsibility. I have also sent my package to Baidu Cloud: link: pan.baidu.com/s/1i52ZO8l Password: 3TT2 made a small contribution, thank you.

I’ve tried the file:// method doesn’t work, so switch to server mode

Switch the command line directory to the current SDK package location

C:\Users\anchengjian\Downloads> mkdir 0.201.
C:\Users\anchengjian\Downloads> cp nwjs-sdk-v020.1.-win-x64.zip ./0.201.Copy the code

Then start the server service, if you have Python directly

C:\Users\anchengjian\Downloads> python -m SimpleHTTPServer 9999Copy the code

Or change position

C:\Users\anchengjian\Downloads> npm install http-server -g
C:\Users\anchengjian\Downloads> http-server -p 9999Copy the code

Once the service is started, you can proceed to the next step. Switch the directory to the project code directory.

Create a.npmrc file with the following contents:

nwjs_build_type=sdk
NWJS_URLBASE=http://localhost:9999/Copy the code

Then install NW directly from NPM

E:\code\vue-webpack-nw> npm i nw --saveCopy the code

At this point, if there are no other problems, it is ready.

2, at this time began to supplement NW related construction

The following paragraphs are directly subtitled by the file name

1) package.json

{
  "name": "vue-webpack-nw"."version": "1.0.0"."description": "vue-webpack-nw"."author": "anchengjian <[email protected]>"."private": true."scripts": {
    "dev": "node build/dev-server.js"."build": "node build/build.js"."lint": "eslint --ext .js,.vue src"
  },
  "dependencies": {
    // ...
  },
  "devDependencies": {
    // ...
  },
  "engines": {
    "node": "> = 7.0.0"."npm": "> = 4.0.0"
  },
  // The following are new additions to nw configuration
  "main": "./index.html"."window": {
    "title": "nw-vue-webpack2"."toolbar": true."frame": true."width": 1200."height": 800."min_width": 800."min_height": 500
  },
  "webkit": {
    "plugin": true
  },
  "node-remote": "http://localhost:8080"
}Copy the code

2) build/webpack.base.conf.js

Adding Basic Configurations

module.exports = {
  // ...
  // The following is a new addition
  target: 'node-webkit'
}Copy the code

3) build/dev-nw.js

Create a new file named dev-nw.js and copy it as follows. I will not talk about the principle, the general function is: Use node.js to change the contents of the current project index.html to the packaged index.html, and then use NW to open the current project directory. When closed or an error occurs, restore the index.html. You can change it yourself. 233333

const path = require('path')
const url = require('url')
const fs = require('fs')
const http = require('http')
const exec = require('child_process').exec
const rootPath = path.resolve(__dirname, '.. / ')
const nwPath = require('nw').findpath()

// Change the addresses of CSS and js in the index.html file
const indexHtmlPath = path.resolve(__dirname, '.. /index.html')
const indexHtmlContent = fs.readFileSync(indexHtmlPath, 'utf-8').toString()

// Restore the original appearance on exit
process.on('exit', exitHandle)
process.on('uncaughtException', exitHandle)

function exitHandle(e) {
  fs.writeFileSync(indexHtmlPath, indexHtmlContent, 'utf-8')
  console.log('233333,bye~~~')}// get uri
var config = require('.. /config')
if(! process.env.NODE_ENV) process.env.NODE_ENV =JSON.parse(config.dev.env.NODE_ENV)
var port = process.env.PORT || config.dev.port
var uri = `http://localhost:${port}/ `

// start lauch NW.js
requestGet(uri, htmlText => {
  htmlText = htmlText.replace('src="/'.`src="${uri}`).replace('href="/'.`href="${uri}`)
  fs.writeFileSync(indexHtmlPath, htmlText, 'utf-8')

  let runNwDev = exec(`${nwPath}. / `, { cwd: rootPath }, (err, stdout, stderr) => {
    if (err) process.exit(0)
  })

  runNwDev.stdout.on('data', (data) => console.log(data))
})

function requestGet(path, callback) {
  console.log('start with request: ', path)
  const options = Object.assign({ method: 'GET' }, url.parse(path))
  const req = http.request(options, res => {
    let body = []
    res.on('data', chunk => body.push(chunk))
    res.on('end', () => callback(Buffer.concat(body).toString()))
  })
  req.on('error', e => console.log('problem with request: ' + e.message))
  req.write(' ')
  req.end()
}Copy the code

4) build/dev-server.js

At the end of the page, you don’t need to open a browser. Instead, you need its code driver to open nw.exe

  // when env is testing, don't need open it
  if(process.env.NODE_ENV ! = ='testing') {
    // opn(uri)

    // modify by anchengjian
    // There is no need to open a browser here, just open nw
    require('./dev-nw')}Copy the code

5) build/dev-client.js

NPM run dev: NPM run dev: NPM run dev: NPM run dev: NPM run dev

GET chrome-extension://hbdgiajgpfdfalonjhdcdmbcmillcjed/__webpack_hmr net::ERR_FILE_NOT_FOUNDCopy the code

Webpack requests are based on the current address of the web page. It’s easy to change the configuration of Webpack-hot-middleware. Have it use __webpack_public_path__ or a global variable every time it makes a request. Also note that path= __webpack_hMR

I’m going to change my hotClient line to look like this

var hotClient = require('webpack-hot-middleware/client? noInfo=true&reload=true&dynamicPublicPath=true&path=__webpack_hmr')Copy the code

This configuration is documented by Webpack-hot-middleware

6) config/index.js

You also need to change the configuration of assetsPublicPath in developer mode; otherwise, __webpack_public_path__ is still /

module.exports = {
  // ...
  dev: {
    env: require('./dev.env'),
    port: 8080.assetsSubDirectory: 'static'.assetsPublicPath: 'http://localhost:8080/'.proxyTable: {},
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false}}Copy the code

At this point, a complete development construct is created, followed by a progressively updated packaging construct of the product pattern.

The original article continues to be updated: blog.anchengjian.com/#/posts/201…