https://www.imooc.com/video/16409 學習視頻,老師的版本和目前版本不一致,問題已解決,如下:
.vue中的文件是和組件一起異步加載的
1 npm i extract-text-webpack-plugin (注意版本)
2webpack.config.js配置
const path = require('path'); const isDev = process.env.NODE_ENV === 'development'; const HTMLPlugin = require('html-webpack-plugin'); const VueLoaderPlugin = require('vue-loader/lib/plugin'); const ExtractPlugin = require('extract-text-webpack-plugin'); //把非js代碼打包成單獨的資源文件,提高效率 const webpack = require('webpack'); const config = { target: 'web', entry: path.join(__dirname, 'src/index.js'), //__dirname 當前文件所在的目錄地址 output: { filename: 'bundle.js', path: path.join(__dirname, 'dist'), }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', }, { test: /\.jsx$/, loader: 'babel-loader', }, { test: /\.(gif|jpg|jpeg|png|svg)$/, use: [ { loader: 'url-loader', options: { limit: 1024, name: '[name]-aaa.[ext]', }, }, ], }, ], }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: isDev ? '"development"' : '"production"', }, }), new VueLoaderPlugin(), new HTMLPlugin(), ], mode: 'development', }; //判斷開發環境和正式環境 cross-env 運行跨平台設置和用環境變量的腳本 if (isDev) { config.module.rules.push({ test: /\.styl/, use: [ 'style-loader', 'css-loader', { loader: 'postcss-loader', options: { sourceMap: true, }, }, 'stylus-loader', ], }); config.devtool = '#cheap-module-eval-source-map'; config.devServer = { port: 8000, host: '0.0.0.0', overlay: { errors: true, }, hot: true, // open: true }; config.plugins.push( new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin() ); } else { //正式環境 config.output.filename = '[name].[chunkhash:8].js'; config.module.rules.push({ test: /\.styl/, use: ExtractPlugin.extract({ fallback: 'style-loader', use: [ 'css-loader', { loader: 'postcss-loader', options: { sourceMap: true, }, }, 'stylus-loader', ], }), }); // config.plugins.push(new ExtractPlugin('styles.[contentHash:8].css'));//這里有問題偶,contentHash是關鍵字,不可使用
config.plugins.push(new ExtractPlugin('styles.[contentHash:hex:8].css'));
}
module.exports = config;
3npm run build
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "cross-env NODE_ENV=production webpack --config webpack.config.js","dev": "cross-env NODE_ENV=development webpack-dev-server --config webpack.config.js" },
4報錯處理
版本問題導致的,webpack4.0以上用3.x extract-webpack-plugin 打包會不兼容,extract-webpack-plugin升級就可以了
解決方法:npm i extract-text-webpack-plugin@4.0.0-beta.0
是因為webpack4.3 包含了contenthash 這個關鍵字段,所以在ExtractPlugin 中不能使用contenthash,
使用mds:contenthash:hex:8 替代