Webpack/Babel/Sass编译到文件夹中



想知道你是否可以帮助-

Webpack让我泪流满面。

我有一个dist文件夹,里面有js、img和css子文件夹。我希望webpack编译我的:src/js/index.js转换为dist/js将我的src/main.scss转换为dist/css。然后我想要webpack-dev-server来监视dist文件,所以如果我在src中进行更改,它会在我工作时立即显示出来。

这听起来很简单,但我花了一天的大部分时间试图实现它。

这就是我的配置文件:

var path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: ['babel-polyfill', './src/js/index.js'], //this is the correct entry point, and I have imported my main.scss into this file
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/main.js'
// it's already going to the dist folder, but is this path correct? I've tried /js/main.js - doesn't work
},
devServer: {
contentBase: './dist'
},
module: {
rules: [
{
test: /.js$/,
use: ['babel-loader']
},
{
test: /.scss$/,
use:  [ MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '/css/styles.css',
}),
new HtmlWebpackPlugin({
inject: false,
hash: true,
template: './src/index.html',
filename: 'index.html'
})
]
}

package.json:

{
"name": "webpack-sass",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack --mode development",
"build": "webpack --mode production",
"start": "webpack-dev-server --mode development --open"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"css-loader": "^1.0.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.4.1",
"node-sass": "^4.9.2",
"sass-loader": "^7.0.3",
"style-loader": "^0.21.0",
"webpack": "^4.16.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.4"
},
"dependencies": {
"babel-polyfill": "^6.26.0"
}
}

用于热重新加载以工作

将此添加到您的网络包文件中

const webpack = require('webpack');

更新

devServer: {
contentBase: './dist'
},

devServer: {
contentBase: './dist'
hot: true,   //this is important
},

然后

new webpack.HotModuleReplacementPlugin()添加到插件部分

plugins: [
new MiniCssExtractPlugin({
filename: '/css/styles.css',
}),
new HtmlWebpackPlugin({
inject: false,
hash: true,
template: './src/index.html',
filename: 'index.html'
}),
new webpack.HotModuleReplacementPlugin()
]

然后在您的index.js

if (module.hot) {
module.hot.accept('./yourImportedComponent.js', function() {
})
}

以上步骤在webpack网站webpack HMR 上有详细解释

最新更新