在我们的Elixir / Phoenix应用程序中,我们最近从brunch移到了webpack(现在是Phoenix的默认设置)。
我们以前是这样在JavaScript中导入CSS的:
import CSS from "./style.css";
哪些人可以访问CSS模块的映射:
console.log(CSS);
{hero: "_page_23f2e__example"}
但是在更改为Webpack之后,CSS
包含一个空对象。即使style.css.json
文件存在并包含映射。
我注意到导入./style.css.json
确实返回了映射,但是这种方法在构建/部署时会引发错误。而且,这似乎并不是Webpack中的默认方式。
我在实现中缺少什么吗?感谢您的帮助!
我创建了一个游乐场回购协议来测试和说明问题: https://github.com/DefactoSoftware/cells_and_modules
我们正在运行Phoenix 1.4.0,Webpack 4.4.0,postcss-modules 1.4.1
我们的应用程序具有以下文件结构:
|– assets
| |– css
| | |– app.css
| |– js
| | |– app.js
|– lib
| |– views
| | |- page
| | | |– index.js
| | | |– style.css
| | | |– template.html.eex
| | | |– view.ex
|– package.json
|– postcss.config.js (setup below)
|– webpack.config.js (setup below)
const path = require("path");
const glob = require("glob");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
module.exports = (env, options) => ({
optimization: {
minimizer: [
new UglifyJsPlugin({ cache: true, parallel: true, sourceMap: false }),
new OptimizeCSSAssetsPlugin({})
]
},
entry: {
app: ["./assets/js/app.js"].concat(
glob.sync("./lib/cells_and_modules_web/views/**/*.css"),
glob.sync("./lib/cells_and_modules_web/views/**/*.js")
)
},
output: {
filename: "js/[name].js",
path: path.resolve(__dirname, "priv/static")
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [
"style-loader",
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
importLoaders: 1
}
},
"postcss-loader"
]
}
]
},
plugins: [
new CleanWebpackPlugin(["priv/static"]),
new MiniCssExtractPlugin({ filename: "css/[name].css" }),
new CopyWebpackPlugin([{ from: "./assets/static/", to: "./" }])
]
});
const path = require("path");
const md5 = require("md5");
module.exports = {
ident: "postcss",
plugins: {
"postcss-modules": {
generateScopedName: function(name, filename, css) {
const relativeFileName = path.relative(process.cwd(), filename);
const directories = path.dirname(filename).split("/");
const directory = directories.slice(-1);
const hash = md5(relativeFileName).substring(0, 5);
return "_" + directory + "_" + hash + "__" + name;
}
}
}
};