У меня такая структура каталогов:
и внутри 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
должны содержать файлы syles и js из всех библиотек, таких как bootstrap и jQuery. Вот что я сделал до сих пор:
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'));
Я могу запустить приложение и правильно отобразить все компоненты, кроме загрузки внешнего файла JS и CSS с помощью webpack
.
Я не очень много разбираюсь в webpack и считаю, что это очень сложно, и я об этом расскажу. Есть несколько простых вопросов:
1- Правильно ли эта конфигурация? Если да, то как я могу включить свои CSS и JS файлы в компоненты с помощью ES6. Что-то вроде ключевого слова import
.
2- Должен ли я использовать webpack для файлов CSS?
3- Как указать отдельные каталоги для ввода и их соответствующие выходные файлы в webpack? Что-то вроде all-custom.js
должно выводиться для custom1.js
и custom2.js
?
Я знаю, что это очень простой вопрос, и я попробовал Google, но не нашел ни одного учебника для Webpack, который прост и нацелен на новичков.
После игры с Webpack в нескольких проектах я понял, как Webpack загружает вещи. Поскольку вопрос по-прежнему остается без ответа, я решил сделать это сам для всех, кто с такой же потребностью.
Структура каталогов
->assets
->css
->my-style-1.css //custom styling file 1
->my-style-2.css //custom styling file 2
->src
->app
->app.js
->variables.js
->libs.js //require all js libraries here
->styles-custom.js //require all custom css files here
->styles-libs.js //require all style libraries here
->node_modules
->index.html
->package.json
->webpack.config.js
Пакет 1 (основной код приложения)
app.js
: предполагается, что это основной файл, и приложение начинается здесь
var msgs = require('./variables');
//similarly import other js files you need in this bundle
//your application code here...
document.getElementById('heading').innerText = msgs.foo;
document.getElementById('sub-heading').innerText = msgs.bar;
Bundle 2 (js modules)
libs.js
: для этого файла потребуются все необходимые модули
require('bootstrap');
//similarly import other js libraries you need in this bundle
Пакет 3 (внешние файлы css)
styles-libs.js
: для этого файла потребуются все внешние файлы css
require('bootstrap/dist/css/bootstrap.css');
//similarly import other css libraries you need in this bundle
Bundle 4 (пользовательские файлы css)
styles-custom.js
: для этого файла потребуются все пользовательские файлы css
require('../assets/css/my-style-1.css');
require('../assets/css/my-style-2.css');
//similarly import other css files you need in this bundle
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const extractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
'app': './src/app/app.js', //specifying bundle with custom js files
'libs': './src/libs.js', //specifying bundle with js libraries
'styles-custom': './src/styles-custom.js', //specifying bundle with custom css files
'styles-libs': './src/styles-libs.js', //specifying bundle with css libraries
},
module: {
loaders: [
//used for loading css files
{
test: /\.css$/,
loader: extractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap' })
},
//used for loading fonts and images
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-loader?name=assets/[name].[hash].[ext]'
}
]
},
output: {
path: path.resolve(__dirname, 'dist'), //directory for output files
filename: '[name].js' //using [name] will create a bundle with same file name as source
},
plugins: [
new extractTextPlugin('[name].css'), //is used for generating css file bundles
//use this for adding jquery
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jQuery'
})
]
}
index.html
<head>
<link rel="stylesheet" href="dist/styles-libs.css" />
<link rel="stylesheet" href="dist/styles-custom.css" />
</head>
<body>
<h2 id="heading"></h2>
<h3>
<label id="sub-heading" class="label label-info"></label>
</h3>
<script src="dist/libs.js"></script>
<script src="dist/app.js"></script>
</body>
import './style.css';
импортировать стиль из './path/style.js';
NB. Обычно вам нужно закодировать в es5 в файле webpack.config.js. Если вы хотите использовать es6, просто следуйте ссылке Как я могу использовать ES6 в webpack.config.js?
Вы можете использовать https://github.com/webpack/css-loader для настройки CSS.
Вы можете использовать разделение кода в веб-пакете и указать несколько точек входа, но они будут генерировать несколько выходных файлов. Посмотрите на несколько разделов точки входа этой ссылки. https://webpack.github.io/docs/code-splitting.html
styles
. Можете ли вы заглянуть в мой код и выяснить, где что-то не так?