【问题标题】:import CSS and JS files using Webpack使用 Webpack 导入 CSS 和 JS 文件
【发布时间】: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-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 教程。

【问题讨论】:

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


【解决方案1】:

在多个项目中使用 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>

【讨论】:

    【解决方案2】:
    1. 您可以在项目的源文件中使用 es6 中的导入来包含 css 和 JS 文件。示例:

    导入'./style.css';

    从'./path/style.js'导入样式;

    注意。一般需要在 webpack.config.js 文件中用 es5 编码。如果你想使用 es6,请点击链接How can I use ES6 in webpack.config.js?

    1. 您可以使用https://github.com/webpack/css-loader 进行CSS 配置。

    2. 您可以在 webpack 中使用代码拆分并指定多个入口点,但这会生成多个输出文件。查看以下链接的多个入口点部分。 https://webpack.github.io/docs/code-splitting.html

    【讨论】:

    • 我做了同样的事情,但是 webpack 没有为styles 生成任何文件。你能看看我的代码并找出问题所在吗?
    • 配置好 webpack.config.js 后可以直接在 client.js 中导入 css。和推荐的配置 webpack.config.js 的方法可以在这里找到github.com/webpack/webpack/issues/1789
    • 能否分享您的完整代码或测试项目,以便我检查。
    猜你喜欢
    • 2015-12-17
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    相关资源
    最近更新 更多