鍍金池/ 問答/HTML5  HTML/ 在vue2.x用webpack打包,構(gòu)建是vue-cli,用npm run bu

在vue2.x用webpack打包,構(gòu)建是vue-cli,用npm run build,項(xiàng)目中內(nèi)聯(lián)的less文件沒有被打包~。

本地啟動是有樣式的~run build就沒有加入內(nèi)聯(lián)less了~

1、webpack.base.conf.js

var path = require('path');
var utils = require('./utils');
var config = require('../config');
var vueLoaderConfig = require('./vue-loader.conf');
var webpack = require("webpack")
// var HtmlWebpackPlugin = require('html-webpack-plugin'); //新增
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const vuxLoader = require('vux-loader');

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}




let webpackBaseConfig = {
  entry: {
    app: './src/main.js'
  },
  // entry: utils.getEntries('./src/module/**/*.js'),
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src')
    }
  },
  module: {
    rules: [
      // {
      //   test: /\.(js|vue)$/,
      //   loader: 'eslint-loader',
      //   enforce: 'pre',
      //   include: [resolve('src'), resolve('test')],
      //   options: {
      //     formatter: require('eslint-friendly-formatter')
      //   }
      // },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      },
      // {
      //   test: /\.css$/,
      //   use: ["vue-style-loader", "css-loader"]
      // },
      {
        test: /\.(less|css)$/,
        use: ExtractTextPlugin.extract({
          use:[ 'css-loader','less-loader'],
          fallback: 'vue-style-loader',
        }),
      },
      {
        test: /\.(scss|sass)$/,
        use: ["node-sass", "vue-style-loader", "css-loader", "sass-loader"]
      }
    ]
  },
  plugins: [
  //   {
  //   name:'duplicate-style'//在構(gòu)建后取出重復(fù)css代碼
  // }
    new webpack.optimize.CommonsChunkPlugin('common.js'),
    new webpack.ProvidePlugin({
      jQuery: "jquery",
      $: "jquery"
    })
  ]
}

module.exports = vuxLoader.merge(webpackBaseConfig, {
  // plugins: ['vux-ui']
  plugins: [
    {
      name: 'vux-ui'
    },
    {
      name: 'duplicate-style'
    }
  // ,
  //   {
  //     //注意這里,這里參照的是vux文檔頁面的設(shè)置,詳情請訪問:https://vux.li/#/zh-CN/README?id=inline-manifest
  //     name: 'inline-manifest'
  //   }
  ]
}
)



2、webpack.prod.conf.jg

var path = require('path')
// var PrerenderSpaPlugin = require('prerender-spa-plugin')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
// var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

var env = process.env.NODE_ENV === 'testing'
  ? require('../config/test.env')
  : config.build.env

var webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css')
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    // new OptimizeCSSPlugin({
    //   cssProcessorOptions: {
    //     safe: true
    //   }
    // }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: process.env.NODE_ENV === 'testing'
        ? 'index.html'
        : config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ]),
    // new PrerenderSpaPlugin(
    //   // 編譯后的html需要存放的路徑
    //   path.join(__dirname, '../dist'),
    //   // 列出哪些路由需要預(yù)渲染
    //   [  '/','/collections' ]
    // )
  ]
})

if (config.build.productionGzip) {
  var CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

/*用于構(gòu)建多頁面*/
// var pages = utils.getEntries('./src/module/**/*.html')
// console.log('===================== multi-pages ===================')
// for(var page in pages) {
//   // 配置生成的html文件,定義路徑等
//   var conf = {
//     filename: page + '.html',
//     template: pages[page], //模板路徑
//     inject: true,
//     // excludeChunks 允許跳過某些chunks, 而chunks告訴插件要引用entry里面的哪幾個入口
//     // 如何更好的理解這塊呢?舉個例子:比如本demo中包含兩個模塊(index和about),最好的當(dāng)然是各個模塊引入自己所需的js,
//     // 而不是每個頁面都引入所有的js,你可以把下面這個excludeChunks去掉,然后npm run build,然后看編譯出來的index.html和about.html就知道了
//     // filter:將數(shù)據(jù)過濾,然后返回符合要求的數(shù)據(jù),Object.keys是獲取JSON對象中的每個key
//     excludeChunks: Object.keys(pages).filter(item => {
//       return (item != page)
//     })
//   }
//   // 需要生成幾個html文件,就配置幾個HtmlWebpackPlugin對象
//   module.exports.plugins.push(new HtmlWebpackPlugin(conf))
// }

module.exports = webpackConfig

3、其中一個組件

<template>
  <div class="resMessage">
    <div>
      <p>{{resMessage}}</p>
    </div>
  </div>
</template>

<script>
  import {mapState} from 'vuex'
  import store from '../store'
  export default{
    name: 'resMessages',
    data(){
      return {}
    },
    computed: {
      ...mapState({
        resMessage: state => {
            console.log("state..",state)
//            setTimeout(function(){
//              store.commit("updateResMessage", {
//                'isShowMessage': false,
//                'resMessage': state.resMessage
//              })
//            },2000);
          return state.resMessage;
        }
      })
    }
  }
</script>

<style lang="less" type="text/less" rel="stylesheet/less" scoped>
  .resMessage {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0rem;
    left: 0rem;
    z-index: 99999;
    background: rgba(0,0,0,.3);
    > div {
      position: relative;
      top:5rem;
      left: 0rem;
      width: 100%;
      height: 2rem;
      line-height: 2rem;
      > p {
        background: rgba(0,0,0,.7);
        border-radius: 5px;
        text-align: center;
        color: #fff;
        font-size:.5rem;
      }
    }

  }
</style>

4、package.json

{
  "name": "novel",
  "version": "1.0.0",
  "description": "Milo",
  "author": "Milo",
  "private": true,
  "scripts": {
    "dev": "node build/dev-server.js",
    "start": "node build/dev-server.js",
    "build": "node build/build.js",
    "unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run",
    "e2e": "node test/e2e/runner.js",
    "test": "npm run unit && npm run e2e"
  },
  "dependencies": {
    "axios": "^0.17.0",
    "less": "^2.7.2",
    "less-loader": "^4.0.4",
    "mint-ui": "^2.2.7",
    "style-loader": "^0.18.2",
    "vue": "^2.3.3",
    "vue-resource": "^1.3.4",
    "vue-router": "^2.3.1",
    "vux": "^2.4.1",
    "vux-loader": "^1.0.69",
    "jquery": "^2.2.3"
  },
  "devDependencies": {
    "autoprefixer": "^6.7.2",
    "babel-core": "^6.22.1",
    "babel-loader": "^6.2.10",
    "babel-plugin-component": "^0.9.1",
    "babel-plugin-istanbul": "^4.1.1",
    "babel-plugin-transform-runtime": "^6.22.0",
    "babel-preset-env": "^1.3.2",
    "babel-preset-stage-2": "^6.22.0",
    "babel-register": "^6.22.0",
    "chai": "^3.5.0",
    "chalk": "^1.1.3",
    "chromedriver": "^2.27.2",
    "connect-history-api-fallback": "^1.3.0",
    "copy-webpack-plugin": "^4.0.1",
    "cross-env": "^4.0.0",
    "cross-spawn": "^5.0.1",
    "css-loader": "^0.28.4",
    "eventsource-polyfill": "^0.9.6",
    "express": "^4.14.1",
    "extract-text-webpack-plugin": "^2.0.0",
    "file-loader": "^0.11.1",
    "friendly-errors-webpack-plugin": "^1.1.3",
    "glob": "^7.1.2",
    "html-webpack-plugin": "^2.28.0",
    "http-proxy-middleware": "^0.17.3",
    "inject-loader": "^3.0.0",
    "karma": "^1.4.1",
    "karma-coverage": "^1.1.1",
    "karma-mocha": "^1.3.0",
    "karma-phantomjs-launcher": "^1.0.2",
    "karma-phantomjs-shim": "^1.4.0",
    "karma-sinon-chai": "^1.3.1",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-spec-reporter": "0.0.30",
    "karma-webpack": "^2.0.2",
    "lolex": "^1.5.2",
    "mocha": "^3.2.0",
    "nightwatch": "^0.9.12",
    "opn": "^4.0.2",
    "optimize-css-assets-webpack-plugin": "^1.3.0",
    "ora": "^1.2.0",
    "phantomjs-prebuilt": "^2.1.14",
    "prerender-spa-plugin": "^2.1.0",
    "rimraf": "^2.6.0",
    "selenium-server": "^3.0.1",
    "semver": "^5.3.0",
    "shelljs": "^0.7.6",
    "sinon": "^2.1.0",
    "sinon-chai": "^2.8.0",
    "url-loader": "^0.5.8",
    "vue-loader": "^12.1.0",
    "vue-style-loader": "^3.0.1",
    "vue-template-compiler": "^2.3.3",
    "vuex": "^2.3.1",
    "vux-loader": "^1.0.69",
    "webpack": "^2.6.1",
    "webpack-bundle-analyzer": "^2.2.1",
    "webpack-dev-middleware": "^1.10.0",
    "webpack-dev-server": "^2.5.0",
    "webpack-hot-middleware": "^2.18.0",
    "webpack-merge": "^4.1.0"
  },
  "engines": {
    "node": ">= 4.0.0",
    "npm": ">= 3.0.0"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ]
}

webpack不懂~這配置那配置,弄的有點(diǎn)亂,看客們耐心點(diǎn)~謝謝了~

回答
編輯回答
墻頭草

1、本地運(yùn)行是可以的,npm start.
2、本地node服務(wù)器也是有相對應(yīng)的樣式,serve -s dist(本地服務(wù)器可以,外網(wǎng)不行)
3、打包build后查看文件,樣式是被打包進(jìn)去的。
4、把組件樣式less轉(zhuǎn)換換成css,同樣是不行,排除less編譯問題。

有2個疑惑,可能是外網(wǎng)服務(wù)器問題,更大可能是webpack打包問題~

//11:50
最新發(fā)現(xiàn),線上的樣式手動添加個空格,就可以顯示~

clipboard.png

clipboard.png

clipboard.png

//12.11 2:09
是nginx解析css要特殊處理,服務(wù)端問題。

2018年3月23日 10:52