【发布时间】:2016-12-25 05:26:05
【问题描述】:
我有一个这样的目录结构:
在 node_modules 内部:
>node_modules
>./bin
>webpack.config.js
>bootstrap
>bootstrap.css
>bootstrap.js
我需要像这样生成单独的 CSS 和 JS 包:
custom-styles.css、custom-js.js、style-libs.css、js-libs.js
其中style-libs 和js-libs 应该包含所有库(如bootstrap 和jQuery)的syles 和js 文件。这是我到目前为止所做的:
webpack.config.js:
const path = require('path');
const basedir = path.join(__dirname, '../../client');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const stylesPath = path.join(__dirname, '../bootstrap/dist/css');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
watch: true,
// Script to bundle using webpack
entry: path.join(basedir, 'src', 'Client.js'),
// Output directory and bundled file
output: {
path: path.join(basedir, 'dist'),
filename: 'app.js'
},
// Configure module loaders (for JS ES6, JSX, etc.)
module: {
// Babel loader for JS(X) files, presets configured in .babelrc
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
babelrc: false,
query: {
presets: ["es2015", "stage-0", "react"],
cacheDirectory: true // TODO: only on development
}
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader")
},
]
},
// Set plugins (for index.html, optimizations, etc.)
plugins: [
// Generate index.html
new HtmlWebpackPlugin({
template: path.join(basedir, 'src', 'index.html'),
filename: 'index.html'
}),
new ExtractTextPlugin(stylesPath + "/bootstrap.css", {
allChunks: true,
})
]
};
Client.js
import * as p from 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
除了使用 webpack 加载外部 JS 和 CSS 文件外,我能够正确运行应用程序并渲染所有组件。
我对 webpack 没有多少经验,并且发现它很难让我听到它。有几个简单的问题:
1- 这个配置正确吗?如果是,那么如何使用 ES6 在组件中包含我的 CSS 和 JS 文件。类似于import 关键字。
2- 我什至应该将 webpack 用于 CSS 文件吗?
3- 如何在 webpack 中为输入和它们各自的输出文件指定单独的目录?应该为custom1.js 和custom2.js 输出类似all-custom.js 的东西?
我知道这些是一些非常基本的问题,我尝试了 Google,但没有找到一个简单且针对初学者的 Webpack 教程。
【问题讨论】:
-
相关:stackoverflow.com/questions/35322958/… 这个答案:stackoverflow.com/questions/35322958/… 似乎是现在使用
MiniCssExtractPlugin的方式。
标签: reactjs webpack webpack-style-loader html-webpack-plugin