Vue – CLI to multi-page application introduction: I have a CLI created vue project, but I want to make a multi-page application, how to do, no more talk, directly open up ~

Convention: Add code between //add and //end Delete (comment) code between //del and //end. A lot of things are written in comments

The first step: Cli A vUE project create a vue project official website vue init webpack demo CLI uses the dev-server service of Webpack by default. You need to manually create a private server called dev.server or dev.client

Step 2: Add two methods to handle the export entry file (SPA default write dead) enter just create vue project CD demo in the directory below find the build/utils.js file modification section:

utils.js ‘use strict’ const path = require(‘path’) const config = require(‘.. /config’) const ExtractTextPlugin = require(‘extract-text-webpack-plugin’) const packageConfig = require(‘.. /package.json’)

//add const glob = require(‘glob’); const HtmlWebpackPlugin = require(‘html-webpack-plugin’); // Const pagePath = path.resolve(__dirname, ‘.. /src/views/’); // The path of the page, such as the views I use here, then the file monitor will start from the views below SRC file //end

exports.assetsPath = function (_path) { const assetsSubDirectory = process.env.NODE_ENV === ‘production’ ? config.build.assetsSubDirectory : config.dev.assetsSubDirectory

return path.posix.join(assetsSubDirectory, _path) }

exports.cssLoaders = function (options) { options = options || {}

const cssLoader = { loader: ‘css-loader’, options: { sourceMap: options.sourceMap } }

const postcssLoader = { loader: ‘postcss-loader’, options: { sourceMap: options.sourceMap } }

// generate loader string to be used with extract text plugin function generateLoaders (loader, loaderOptions) { const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]

if (loader) { loaders.push({ loader: loader + '-loader', options: Object.assign({}, loaderOptions, { sourceMap: options.sourceMap }) }) } // Extract CSS when that option is specified // (which is the case during production build) if  (options.extract) { return ExtractTextPlugin.extract({ use: loaders, fallback: 'vue-style-loader' }) } else { return ['vue-style-loader'].concat(loaders) }Copy the code

}

/ / vue-loader.vuejs.org/en/configur… return { css: generateLoaders(), postcss: generateLoaders(), less: generateLoaders(‘less’), sass: generateLoaders(‘sass’, { indentedSyntax: true }), scss: generateLoaders(‘sass’), stylus: generateLoaders(‘stylus’), styl: generateLoaders(‘stylus’) } }

// Generate loaders for standalone style files (outside of .vue) exports.styleLoaders = function (options) { const output = [] const loaders = exports.cssLoaders(options)

for (const extension in loaders) { const loader = loaders[extension] output.push({ test: new RegExp(‘\.’ + extension + ‘$’), use: loader }) }

return output }

exports.createNotifierCallback = () => { const notifier = require(‘node-notifier’)

return (severity, errors) => { if (severity ! == ‘error’) return

const error = errors[0] const filename = error.file && error.file.split('! ').pop() notifier.notify({ title: packageConfig.name, message: severity + ': ' + error.name, subtitle: filename || '', icon: path.join(__dirname, 'logo.png') })Copy the code

}}

Exports.createentry = () => {let files = glob.sync(pagePath + ‘/**/*.js’); //add a new method to handle exports.createEntry = () => {let files = glob.sync(pagePath + ‘/**/*.js’); let entries = {}; let basename; let foldername;

files.forEach(entry => { // Filter the router.js basename = path.basename(entry, path.extname(entry), ‘router.js’); foldername = path.dirname(entry).split(‘/’).splice(-1)[0]; // If foldername not equal basename, doing nothing // The folder maybe contain more js files, but only the same name is main if (basename === foldername) { entries[basename] = process.env.NODE_ENV === ‘development’ ? [ ‘webpack-hot-middleware/client?noInfo=true&reload=true&path=/__webpack_hmr&timeout=20000’, entry ]: [entry]; }}); return entries; }; //end

/ / add new exports. Export file createHtmlWebpackPlugin = (publicModule) = > {let files = glob. Sync (pagePath + ‘/ * * / *. HTML’, {matchBase: true}); let entries = exports.createEntry(); let plugins = []; let conf; let basename; let foldername; publicModule = publicModule || [];

files.forEach(file => { basename = path.basename(file, path.extname(file)); foldername = path.dirname(file).split(‘/’).splice(-1).join(”);

if (basename === foldername) { conf = { template: file, filename: basename + '.html', inject: true, chunks: entries[basename] ? [basename] : [] }; if (process.env.NODE_ENV ! == 'development') { conf.chunksSortMode = 'dependency'; conf.minify = { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }; // When building a production environment, you need to specify the common module conf.chunks = [...publicModule,...conf.chunks]; } plugins.push(new HtmlWebpackPlugin(conf)); }Copy the code

}); return plugins; }; //end 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 ‘use strict’ const path = require(‘path’) const config = require(‘.. /config’) const ExtractTextPlugin = require(‘extract-text-webpack-plugin’) const packageConfig = require(‘.. /package.json’)

//add const glob = require(‘glob’); const HtmlWebpackPlugin = require(‘html-webpack-plugin’); // Const pagePath = path.resolve(__dirname, ‘.. /src/views/’); // The path of the page, such as the views I use here, then the file monitor will start from the views below SRC file //end

exports.assetsPath = function (_path) { const assetsSubDirectory = process.env.NODE_ENV === ‘production’ ? config.build.assetsSubDirectory : config.dev.assetsSubDirectory

return path.posix.join(assetsSubDirectory, _path) }

exports.cssLoaders = function (options) { options = options || {}

const cssLoader = { loader: ‘css-loader’, options: { sourceMap: options.sourceMap } }

const postcssLoader = { loader: ‘postcss-loader’, options: { sourceMap: options.sourceMap } }

// generate loader string to be used with extract text plugin function generateLoaders (loader, loaderOptions) { const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]

if (loader) { loaders.push({ loader: loader + '-loader', options: Object.assign({}, loaderOptions, { sourceMap: options.sourceMap }) }) } // Extract CSS when that option is specified // (which is the case during production build) if  (options.extract) { return ExtractTextPlugin.extract({ use: loaders, fallback: 'vue-style-loader' }) } else { return ['vue-style-loader'].concat(loaders) }Copy the code

}

/ / vue-loader.vuejs.org/en/configur… return { css: generateLoaders(), postcss: generateLoaders(), less: generateLoaders(‘less’), sass: generateLoaders(‘sass’, { indentedSyntax: true }), scss: generateLoaders(‘sass’), stylus: generateLoaders(‘stylus’), styl: generateLoaders(‘stylus’) } }

// Generate loaders for standalone style files (outside of .vue) exports.styleLoaders = function (options) { const output = [] const loaders = exports.cssLoaders(options)

for (const extension in loaders) { const loader = loaders[extension] output.push({ test: new RegExp(‘\.’ + extension + ‘$’), use: loader }) }

return output }

exports.createNotifierCallback = () => { const notifier = require(‘node-notifier’)

return (severity, errors) => { if (severity ! == ‘error’) return

const error = errors[0] const filename = error.file && error.file.split('! ').pop() notifier.notify({ title: packageConfig.name, message: severity + ': ' + error.name, subtitle: filename || '', icon: path.join(__dirname, 'logo.png') })Copy the code

}}

Exports.createentry = () => {let files = glob.sync(pagePath + ‘/**/*.js’); //add a new method to handle exports.createEntry = () => {let files = glob.sync(pagePath + ‘/**/*.js’); let entries = {}; let basename; let foldername;

files.forEach(entry => { // Filter the router.js basename = path.basename(entry, path.extname(entry), ‘router.js’); foldername = path.dirname(entry).split(‘/’).splice(-1)[0]; // If foldername not equal basename, doing nothing // The folder maybe contain more js files, but only the same name is main if (basename === foldername) { entries[basename] = process.env.NODE_ENV === ‘development’ ? [ ‘webpack-hot-middleware/client?noInfo=true&reload=true&path=/__webpack_hmr&timeout=20000’, entry ]: [entry]; }}); return entries; }; //end

/ / add new exports. Export file createHtmlWebpackPlugin = (publicModule) = > {let files = glob. Sync (pagePath + ‘/ * * / *. HTML’, {matchBase: true}); let entries = exports.createEntry(); let plugins = []; let conf; let basename; let foldername; publicModule = publicModule || [];

files.forEach(file => { basename = path.basename(file, path.extname(file)); foldername = path.dirname(file).split(‘/’).splice(-1).join(”);

if (basename === foldername) { conf = { template: file, filename: basename + '.html', inject: true, chunks: entries[basename] ? [basename] : [] }; if (process.env.NODE_ENV ! == 'development') { conf.chunksSortMode = 'dependency'; conf.minify = { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }; // When building a production environment, you need to specify the common module conf.chunks = [...publicModule,...conf.chunks]; } plugins.push(new HtmlWebpackPlugin(conf)); }Copy the code

}); return plugins; }; //end step 3: Create a private server (do not use the dev-server service, create a private server) from express and configure (build folder webpack.dev.client.js)

webpack.dev.client.js /**

  • created by qbyu2 on 2018-05-30
  • Express servers
  • */ ‘use strict’;

const fs = require(‘fs’); const path = require(‘path’); const express = require(‘express’); const webpack = require(‘webpack’); const webpackDevMiddleware = require(‘webpack-dev-middleware’); Const webpackHotMiddleware = require(‘webpack-hot-middleware’); // const config = require(‘.. /config’); const devWebpackConfig = require(‘./webpack.dev.conf’); const proxyMiddleware = require(‘http-proxy-middleware’); / / across domains

const proxyTable = config.dev.proxyTable;

const PORT = config.dev.port; const HOST = config.dev.host; const assetsRoot = config.dev.assetsRoot; const app = express(); const router = express.Router(); const compiler = webpack(devWebpackConfig);

let devMiddleware = webpackDevMiddleware(compiler, { publicPath: devWebpackConfig.output.publicPath, quiet: true, stats: { colors: true, chunks: false } });

let hotMiddleware = webpackHotMiddleware(compiler, { path: ‘/__webpack_hmr’, heartbeat: 2000 });

app.use(hotMiddleware); app.use(devMiddleware);

Object.keys(proxyTable).forEach(function (context) { let options = proxyTable[context]; if (typeof options === ‘string’) { options = { target: options }; } app.use(proxyMiddleware(context, options)); });

Use (router) app.use(‘/static’, express.static(path.join(assetsRoot, ‘static’)));

let sendFile = (viewname, response, next) => { compiler.outputFileSystem.readFile(viewname, (err, result) => { if (err) { return (next(err)); } response.set(‘content-type’, ‘text/html’); response.send(result); response.end(); }); };

Function pathJoin(patz) {return path.join(assetsRoot, patz); }

/ * *

  • Define routes (private routes not VUE routes)
  • * /

// favicon router.get(‘/favicon.ico’, (req, res, next) => { res.end(); });

// http://localhost:8080/ router.get(‘/’, (req, res, next)=>{ sendFile(pathJoin(‘index.html’), res, next); });

// http://localhost:8080/home router.get(‘/:home’, (req, res, next) => { sendFile(pathJoin(req.params.home + ‘.html’), res, next); });

// http://localhost:8080/index router.get(‘/:index’, (req, res, next) => { sendFile(pathJoin(req.params.index + ‘.html’), res, next); });

module.exports = app.listen(PORT, err => { if (err){ return } console.log(Listening at http://${HOST}:${PORT}\n); }) 12 34 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 99 100 101 102 /**

  • created by qbyu2 on 2018-05-30
  • Express servers
  • */ ‘use strict’;

const fs = require(‘fs’); const path = require(‘path’); const express = require(‘express’); const webpack = require(‘webpack’); const webpackDevMiddleware = require(‘webpack-dev-middleware’); Const webpackHotMiddleware = require(‘webpack-hot-middleware’); // const config = require(‘.. /config’); const devWebpackConfig = require(‘./webpack.dev.conf’); const proxyMiddleware = require(‘http-proxy-middleware’); / / across domains

const proxyTable = config.dev.proxyTable;

const PORT = config.dev.port; const HOST = config.dev.host; const assetsRoot = config.dev.assetsRoot; const app = express(); const router = express.Router(); const compiler = webpack(devWebpackConfig);

let devMiddleware = webpackDevMiddleware(compiler, { publicPath: devWebpackConfig.output.publicPath, quiet: true, stats: { colors: true, chunks: false } });

let hotMiddleware = webpackHotMiddleware(compiler, { path: ‘/__webpack_hmr’, heartbeat: 2000 });

app.use(hotMiddleware); app.use(devMiddleware);

Object.keys(proxyTable).forEach(function (context) { let options = proxyTable[context]; if (typeof options === ‘string’) { options = { target: options }; } app.use(proxyMiddleware(context, options)); });

Use (router) app.use(‘/static’, express.static(path.join(assetsRoot, ‘static’)));

let sendFile = (viewname, response, next) => { compiler.outputFileSystem.readFile(viewname, (err, result) => { if (err) { return (next(err)); } response.set(‘content-type’, ‘text/html’); response.send(result); response.end(); }); };

Function pathJoin(patz) {return path.join(assetsRoot, patz); }

/ * *

  • Define routes (private routes not VUE routes)
  • * /

// favicon router.get(‘/favicon.ico’, (req, res, next) => { res.end(); });

// http://localhost:8080/ router.get(‘/’, (req, res, next)=>{ sendFile(pathJoin(‘index.html’), res, next); });

// http://localhost:8080/home router.get(‘/:home’, (req, res, next) => { sendFile(pathJoin(req.params.home + ‘.html’), res, next); });

// http://localhost:8080/index router.get(‘/:index’, (req, res, next) => { sendFile(pathJoin(req.params.index + ‘.html’), res, next); });

module.exports = app.listen(PORT, err => { if (err){ return } console.log(Listening at http://${HOST}:${PORT}\n); }) private server created well under installation dependency has pit… NPM install [email protected] — save-dev NPM install webpack-dev-middleware — save-dev NPM install [email protected] — save-dev NPM install http-proxy-middleware — save-dev

Step 4: Conf. Js ‘use strict’ const utils = require(‘./utils’) const webpack = require(‘webpack’) const config = require(‘.. /config’) const merge = require(‘webpack-merge’) const path = require(‘path’) const baseWebpackConfig = require(‘./webpack.base.conf’) const CopyWebpackPlugin = require(‘copy-webpack-plugin’) const HtmlWebpackPlugin = require(‘html-webpack-plugin’) const FriendlyErrorsPlugin = require(‘friendly-errors-webpack-plugin’) const portfinder = require(‘portfinder’)

const HOST = process.env.HOST const PORT = process.env.PORT && Number(process.env.PORT)

const devWebpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) }, // cheap-module-eval-source-map is faster for development devtool: config.dev.devtool,

// these devServer options should be customized in /config/index.js devServer: { clientLogLevel: ‘warning’, historyApiFallback: { rewrites: [ { from: /./, to: path.posix.join(config.dev.assetsPublicPath, ‘index.html’) }, ], }, hot: true, contentBase: false, // since we use CopyWebpackPlugin. compress: true, host: HOST || config.dev.host, port: PORT || config.dev.port, open: config.dev.autoOpenBrowser, overlay: config.dev.errorOverlay ? { warnings: false, errors: true } : false, publicPath: config.dev.assetsPublicPath, proxy: config.dev.proxyTable, quiet: true, // necessary for FriendlyErrorsPlugin watchOptions: { poll: config.dev.poll, } }, plugins: [ new webpack.DefinePlugin({ ‘process.env’: require(‘../config/dev.env’) }), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), / / HMR shows correct file names in the console on the update. The new webpack. NoEmitOnErrorsPlugin (), / / github.com/ampedandwir… // new HtmlWebpackPlugin({// filename: ‘index.html’, // template: ‘index.html’, // inject: true // }), //end // copy custom static assets new CopyWebpackPlugin([ { from: path.resolve(__dirname, ‘../static’), to: config.dev.assetsSubDirectory, ignore: [‘.’] } ]) ] //add .concat(utils.createHtmlWebpackPlugin()) //end }) //del // module.exports = new Promise((resolve, reject) => { // portfinder.basePort = process.env.PORT || config.dev.port // portfinder.getPort((err, port) => { // if (err) { // reject(err) // } else { // // publish the new Port, necessary for e2e tests // process.env.PORT = port // // add port to devServer config // devWebpackConfig.devServer.port = port // // // Add FriendlyErrorsPlugin // devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ // compilationSuccessInfo: { // messages: [Your application is running here: http://${devWebpackConfig.devServer.host}:${port}], // }, // onErrors: config.dev.notifyOnErrors // ? utils.createNotifierCallback() // : undefined // })) // // resolve(devWebpackConfig) // } // }) // }) //end 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 ‘use strict’ const utils = require(‘./utils’) const webpack = require(‘webpack’) const config = require(‘.. /config’) const merge = require(‘webpack-merge’) const path = require(‘path’) const baseWebpackConfig = require(‘./webpack.base.conf’) const CopyWebpackPlugin = require(‘copy-webpack-plugin’) const HtmlWebpackPlugin = require(‘html-webpack-plugin’) const FriendlyErrorsPlugin = require(‘friendly-errors-webpack-plugin’) const portfinder = require(‘portfinder’)

const HOST = process.env.HOST const PORT = process.env.PORT && Number(process.env.PORT)

const devWebpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) }, // cheap-module-eval-source-map is faster for development devtool: config.dev.devtool,

// these devServer options should be customized in /config/index.js devServer: { clientLogLevel: ‘warning’, historyApiFallback: { rewrites: [ { from: /./, to: path.posix.join(config.dev.assetsPublicPath, ‘index.html’) }, ], }, hot: true, contentBase: false, // since we use CopyWebpackPlugin. compress: true, host: HOST || config.dev.host, port: PORT || config.dev.port, open: config.dev.autoOpenBrowser, overlay: config.dev.errorOverlay ? { warnings: false, errors: true } : false, publicPath: config.dev.assetsPublicPath, proxy: config.dev.proxyTable, quiet: true, // necessary for FriendlyErrorsPlugin watchOptions: { poll: config.dev.poll, } }, plugins: [ new webpack.DefinePlugin({ ‘process.env’: require(‘../config/dev.env’) }), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), / / HMR shows correct file names in the console on the update. The new webpack. NoEmitOnErrorsPlugin (), / / github.com/ampedandwir… // new HtmlWebpackPlugin({// filename: ‘index.html’, // template: ‘index.html’, // inject: true // }), //end // copy custom static assets new CopyWebpackPlugin([ { from: path.resolve(__dirname, ‘../static’), to: config.dev.assetsSubDirectory, ignore: [‘.’] } ]) ] //add .concat(utils.createHtmlWebpackPlugin()) //end }) //del // module.exports = new Promise((resolve, reject) => { // portfinder.basePort = process.env.PORT || config.dev.port // portfinder.getPort((err, port) => { // if (err) { // reject(err) // } else { // // publish the new Port, necessary for e2e tests // process.env.PORT = port // // add port to devServer config // devWebpackConfig.devServer.port = port // // // Add FriendlyErrorsPlugin // devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ // compilationSuccessInfo: { // messages: [Your application is running here: http://${devWebpackConfig.devServer.host}:${port}], // }, // onErrors: config.dev.notifyOnErrors // ? utils.createNotifierCallback() // : undefined // })) // // resolve(devWebpackConfig) // } // }) // }) //end webpack.dev.conf.js ‘use strict’ const utils = require(‘./utils’) const webpack = require(‘webpack’) const config = require(‘.. /config’) const merge = require(‘webpack-merge’) const path = require(‘path’) const baseWebpackConfig = require(‘./webpack.base.conf’) const CopyWebpackPlugin = require(‘copy-webpack-plugin’) const HtmlWebpackPlugin = require(‘html-webpack-plugin’) const FriendlyErrorsPlugin = require(‘friendly-errors-webpack-plugin’) const portfinder = require(‘portfinder’)

process.env.NODE_ENV = ‘development’;

const HOST = process.env.HOST const PORT = process.env.PORT && Number(process.env.PORT)

const devWebpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) }, // cheap-module-eval-source-map is faster for development devtool: config.dev.devtool,

// These devServer options should be customized in /config/index.js //del Note SPA server // devServer: {// clientLogLevel: ‘warning’, // historyApiFallback: { // rewrites: [ // { from: /./, to: path.posix.join(config.dev.assetsPublicPath, ‘index.html’) }, // ], // }, // hot: true, // contentBase: false, // since we use CopyWebpackPlugin. // compress: true, // host: HOST || config.dev.host, // port: PORT || config.dev.port, // open: config.dev.autoOpenBrowser, // overlay: config.dev.errorOverlay // ? { warnings: false, errors: true } // : false, // publicPath: config.dev.assetsPublicPath, // proxy: config.dev.proxyTable, // quiet: true, // necessary for FriendlyErrorsPlugin // watchOptions: { // poll: config.dev.poll, // } // }, //end plugins: [ new webpack.DefinePlugin({ ‘process.env’: require(‘../config/dev.env’) }), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), / / HMR shows correct file names in the console on the update. The new webpack. NoEmitOnErrorsPlugin (), / / github.com/ampedandwir… // new HtmlWebpackPlugin({// filename: ‘index.html’, // template: ‘index.html’, // inject: true // }), //end // copy custom static assets new CopyWebpackPlugin([ { from: path.resolve(__dirname, ‘../static’), to: config.dev.assetsSubDirectory, ignore: [‘.’] } ]) ] //add .concat(utils.createHtmlWebpackPlugin()) //end }) //del // module.exports = new Promise((resolve, reject) => { // portfinder.basePort = process.env.PORT || config.dev.port // portfinder.getPort((err, port) => { // if (err) { // reject(err) // } else { // // publish the new Port, necessary for e2e tests // process.env.PORT = port // // add port to devServer config // devWebpackConfig.devServer.port = port // // // Add FriendlyErrorsPlugin // devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ // compilationSuccessInfo: { // messages: [Your application is running here: http://${devWebpackConfig.devServer.host}:${port}], // }, // onErrors: config.dev.notifyOnErrors // ? utils.createNotifierCallback() // : undefined // })) // // resolve(devWebpackConfig) // } // }) // }) //end module.exports = devWebpackConfig; 12 34 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 ‘use strict’ const utils = require(‘./utils’) const webpack = require(‘webpack’) const config = require(‘.. /config’) const merge = require(‘webpack-merge’) const path = require(‘path’) const baseWebpackConfig = require(‘./webpack.base.conf’) const CopyWebpackPlugin = require(‘copy-webpack-plugin’) const HtmlWebpackPlugin = require(‘html-webpack-plugin’) const FriendlyErrorsPlugin = require(‘friendly-errors-webpack-plugin’) const portfinder = require(‘portfinder’)

process.env.NODE_ENV = ‘development’;

const HOST = process.env.HOST const PORT = process.env.PORT && Number(process.env.PORT)

const devWebpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) }, // cheap-module-eval-source-map is faster for development devtool: config.dev.devtool,

// These devServer options should be customized in /config/index.js //del Note SPA server // devServer: {// clientLogLevel: ‘warning’, // historyApiFallback: { // rewrites: [ // { from: /./, to: path.posix.join(config.dev.assetsPublicPath, ‘index.html’) }, // ], // }, // hot: true, // contentBase: false, // since we use CopyWebpackPlugin. // compress: true, // host: HOST || config.dev.host, // port: PORT || config.dev.port, // open: config.dev.autoOpenBrowser, // overlay: config.dev.errorOverlay // ? { warnings: false, errors: true } // : false, // publicPath: config.dev.assetsPublicPath, // proxy: config.dev.proxyTable, // quiet: true, // necessary for FriendlyErrorsPlugin // watchOptions: { // poll: config.dev.poll, // } // }, //end plugins: [ new webpack.DefinePlugin({ ‘process.env’: require(‘../config/dev.env’) }), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), / / HMR shows correct file names in the console on the update. The new webpack. NoEmitOnErrorsPlugin (), / / github.com/ampedandwir… // new HtmlWebpackPlugin({// filename: ‘index.html’, // template: ‘index.html’, // inject: true // }), //end // copy custom static assets new CopyWebpackPlugin([ { from: path.resolve(__dirname, ‘../static’), to: config.dev.assetsSubDirectory, ignore: [‘.’] } ]) ] //add .concat(utils.createHtmlWebpackPlugin()) //end }) //del // module.exports = new Promise((resolve, reject) => { // portfinder.basePort = process.env.PORT || config.dev.port // portfinder.getPort((err, port) => { // if (err) { // reject(err) // } else { // // publish the new Port, necessary for e2e tests // process.env.PORT = port // // add port to devServer config // devWebpackConfig.devServer.port = port // // // Add FriendlyErrorsPlugin // devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ // compilationSuccessInfo: { // messages: [Your application is running here: http://${devWebpackConfig.devServer.host}:${port}], // }, // onErrors: config.dev.notifyOnErrors // ? utils.createNotifierCallback() // : undefined // })) // // resolve(devWebpackConfig) // } // }) // }) //end module.exports = devWebpackConfig; Webpack. Prod. Conf. Js plugins add finally. Concat (utils. CreateHtmlWebpackPlugin ([‘ manifest ‘, ‘vendor’])) as the test environment

Step 5: Modify the package.json command to configure scripts’ dev ‘: this will not be executed using the default dev-server instead of your private server

“scripts”: { “dev”: “node build/webpack.dev.client.js”, “start”: “npm run dev”, “build”: “node build/build.js” }, 1 2 3 4 5 “scripts”: { “dev”: “node build/webpack.dev.client.js”, “start”: “npm run dev”, “build”: “Node build/build.js”}, step 6: Create a test file in the SRC directory and create a new folder named Views (you can name it as you like in the code comments). Create two new folders in the views folder named Index and HOME, which represent multiple pages

Package to relative path config/index.js below build

assetsPublicPath: ‘/’, => assetsPublicPath: ‘./’, 1 assetsPublicPath: ‘/’, => assetsPublicPath: ‘./’, 3073784422-5b0f614823a7c_articlex

Finally, NPM run dev or NPM run build

The test environment is almost the same as the production environment, just a few configuration parameters are not the same this time you will find, what the hell the article reported wrong ah wait for a moment, don’t be angry ~ two places,

App. use(router) app.use(‘/static’, express.static(path.join(assetsRoot, ‘static’))); Use (router) app.use(router) app.use(‘/static’, express.static(path.join(assetsRoot, ‘static’))); This assetsRoot is not available when the cli was created. Find dev plus under config/index.js

assetsRoot: path.resolve(__dirname, ‘.. /dist’), 1 assetsRoot: path.resolve(__dirname, ‘.. /dist’), 4198209571-5b0f69a5de0e6_articlex

The default version of Webpack-dev-Middleware is 3.1.3, but it doesn’t work. I don’t know which version doesn’t work

context.compiler.hooks.invalid.tap(‘WebpackDevMiddleware’, invalid); 1 context.compiler.hooks.invalid.tap(‘WebpackDevMiddleware’, invalid); Uninstall Webpack-dev – Middleware

NPM uninstall webpack-dev-middleware 1 NPM uninstall webpack-dev-middleware uses webpack-dev-middleware shipped with dev-server (Single-page CLI applications are hot loaded.) Reinstall dev-server

NPM install [email protected] –save-dev 1 NPM install [email protected] –save-dev NPM run dev 1 NPM Summary: Run dev 1510784734-5b0f6b3D09383_articlex 1950268177-5b0F6B5628e02_articlex 1950268177-5b0f6B5628e02 Cli a vue demo project from scratch again in the actual project use, rather than copy run no problem fix ~ suggestion just, you how to beat people, whoo-hoo ~

Holiday is coming, if you think this article is useful to you, please feel free to tip, so that the author can buy a lollipop to eat ~

— — — — — — — – 6.1 more — — — — — — — — left a crater, one day, has great collection, didn’t see people commented pit, heartache cannot breathe ~

No common modules are introduced after build

Code has been updated ~ build after normal access…