如何使用ngnix在生产中提供webpack构建文件

时间:2016-12-28 08:25:01

标签: node.js nginx webpack vuejs2

我写了一个vue + webpack项目,它在webpack-dev-middleware中工作正常。现在我想用nginx部署它。我所做的是编写webpack.build.config.js并将所有文件捆绑到dist文件夹中。然后我将dist文件夹复制到nginx html文件夹中,并在nginx.conf中分配索引。但是,它有一个错误说:

  

[Vue警告]:无法安装组件:模板或渲染功能   定义。 (在根实例中找到)

我是devops / backend的新手,并且与整体构建或部署过程相当混淆。 webpack-dev-server或nodejs在生产环境中是否仍然需要?我的生产环境后端是nginx / PHP和IIS / .Net,现在根本没有安装节点。

我的nginx.conf是

location / {
    root   html/dist;
    index  index.html index.htm;
}

webpack.build.config.js是

var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var public_dir = "components";
//var ModernizrWebpackPlugin = require('modernizr-webpack-plugin');

module.exports = {
    entry: [
        path.join(__dirname,'./index.js')
    ],
    output: {
        path: path.join(__dirname, '/dist/'),
        filename: '[name].js',
        publicPath: '/'
    },
    devtool: 'eval-source-map',
    plugins: [
        new webpack.optimize.CommonsChunkPlugin('common.js'),
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.UglifyJsPlugin(),
        new webpack.optimize.AggressiveMergingPlugin(),
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: path.resolve(__dirname, 'index.html'),
            inject: true
        })
    ],
    resolve: {
        root: [path.resolve('./components')],
        extensions: ['', '.js', '.css']
    },
    module: {
        loaders: [
        ]
    }
};

构建时我运行

  

webpack -p --config ./webpack.build.config.js

1 个答案:

答案 0 :(得分:0)

我正在使用vue-cli初始化vuejs webpack项目。该项目已经有构建脚本,您可以参考:

require('./check-versions')()

process.env.NODE_ENV = 'production'

var ora = require('ora')
var rm = require('rimraf')
var path = require('path')
var chalk = require('chalk')
var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf')

var spinner = ora('building for production...')
spinner.start()

rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  if (err) throw err
  webpack(webpackConfig, function (err, stats) {
    spinner.stop()
    if (err) throw err
    process.stdout.write(stats.toString({
      colors: true,
      modules: false,
      children: false,
      chunks: false,
      chunkModules: false
    }) + '\n\n')

    console.log(chalk.cyan('  Build complete.\n'))
    console.log(chalk.yellow(
      '  Tip: built files are meant to be served over an HTTP server.\n' +
      '  Opening index.html over file:// won\'t work.\n'
    ))
  })
})

构建完成后,我们将有一个dist文件夹。将所有文件上传到Nginx的html文件夹(默认) 配置根路径以使用完整路径,如下所示:

listen      80;
server_name mydomain www.mydomain;
root /var/www/html;