reactjs - 使用 Webpack 导入 CSS 和 JS 文件

标签 reactjs webpack webpack-style-loader html-webpack-plugin

我有这样的目录结构:

enter image description here

以及node_modules内部:

 >node_modules
  >./bin
   >webpack.config.js
  >bootstrap
   >bootstrap.css
   >bootstrap.js

我需要生成单独的 CSS 和 JS 包,如下所示:

自定义样式.css、自定义js.js、样式libs.css、js-libs.js

其中 style-libsjs-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.jscustom2.js 应该输出类似 all-custom.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

Bundle 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 模块)

libs.js:此文件将需要所需的所有模块

require('bootstrap');
//similarly import other js libraries you need in this bundle

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>

关于reactjs - 使用 Webpack 导入 CSS 和 JS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39015521/

相关文章:

javascript - 优化 React-Redux 连接的 PureComponent

reactjs - 修复react create app第三方导入中未定义 'define' no-undef

jquery - ProvidePlugin 不适用于 jquery

npm - 构建 :Cannot find type definition file for webpack-env

css - 背景图像 URL 未使用 Webpack 加载

ecmascript-6 - 如何使用 Webpack 删除/取消导入内联 CSS?

reactjs - 如何在 typescript 中使用 Highcharts 并使用react

javascript - 服务器 : how to get "window", "location"和其他 "window"属性以及通常是浏览器对象上的浏览器代码?

reactjs - 在 React 中关注(滚动到)一个 DIV 元素

css - gulp + webpack + css-loader + typescript : "cannot find module"